Ruby on rails - 静态方法

Posted

技术标签:

【中文标题】Ruby on rails - 静态方法【英文标题】:Ruby on rails - Static method 【发布时间】:2011-07-11 00:47:11 【问题描述】:

我希望每 5 分钟执行一次方法,我每次都为 ruby​​ (cron) 实现。但它不起作用。我认为我的方法无法访问。 我要执行的方法位于一个类中。我想我必须将该方法设为静态,以便我可以使用MyClass.MyMethod 访问它。但我找不到正确的语法,或者我找错地方了。

Schedule.rb

every 5.minutes do
  runner "Ping.checkPings"
end

Ping.rb

def checkPings      
  gate =  Net::Ping::External.new("10.10.1.1")
  @monitor_ping = Ping.new()

  if gate.ping?        
    MonitorPing.WAN = true
  else 
    MonitorPing.WAN = false
  end

  @monitor_ping.save      
end

【问题讨论】:

【参考方案1】:

有一些方法可以在 RoR 中声明静态方法。

#1

class YourClassName
  class << self
    def your_static_method (params)
      # Your code here
    end
  end
end

#2

class YourClassName
  def self.your_status_method
    // Your code here
  end
end

【讨论】:

【参考方案2】:

您可以创建一个从 self 扩展的块并在其中定义您的静态方法,而不是为整个类扩展 self

你会做这样的事情:

class << self
#define static methods here
end

所以在你的例子中,你会做这样的事情:

class Ping
  class << self
    def checkPings
      #do you ping code here
      # checkPings is a static method
    end
  end
end

你可以这样称呼它:Ping.checkPings

【讨论】:

【参考方案3】:

您可以像这样在 Ruby 中使用静态方法:

class MyModel
    def self.do_something
        puts "this is a static method"
    end
end
MyModel.do_something  # => "this is a static method"
MyModel::do_something # => "this is a static method"

另外请注意,您的方法使用了错误的命名约定。它应该是check_pings,但这不会影响您的代码是否有效,它只是 ruby​​ 样式。

【讨论】:

您应该按照建议更改方法的名称 - 当您稍后再看这段代码时,它确实很重要。这对于必须阅读该代码的其他人来说很重要——通常是为了找出(任何)代码不起作用(谁习惯于常规风格——这是我认识的每个使用 Ruby 编程的人)。【参考方案4】:

要声明一个静态方法,请写...

def self.checkPings
  # A static method
end

...或...

class Myclass extend self

  def checkPings
    # Its static method
  end

end

【讨论】:

我无法重现后一个示例def checkPings extend self。这是有效的语法吗? 你的类必须扩展 self 以使类内部的所有方法都是静态的。 @Ashish 你确定不应该是class MyClass &lt; self【参考方案5】:

Ruby 中不能有静态方法。在 Ruby 中,所有方法都是动态的。 Ruby 中只有一种方法:动态实例方法。

真的,术语静态方法 无论如何都是用词不当。静态方法是一种不与任何对象关联且不动态调度的方法(因此是“静态”),但这两个方法几乎是“方法”的定义 ”。我们已经为这个构造起了一个很好的名字:procedure

【讨论】:

投反对票;语义。 Ruby 的方法可能不是“静态的”,但 OP 只想要一个在 ruby​​ 中完全可行的类级函数(例如 MyClass::doThing())。 “你不能在 ruby​​ 中做到这一点”没有帮助。 正确,但对“方法”一词非常挑剔。你知道他们的意思。【参考方案6】:

更改您的代码
class MyModel
  def checkPings
  end
end

class MyModel
  def self.checkPings
  end
end

注意在方法名中添加了self。

def checkPings 是 MyModel 类的实例方法,而 def self.checkPings 是类方法。

【讨论】:

以上是关于Ruby on rails - 静态方法的主要内容,如果未能解决你的问题,请参考以下文章

Ruby on Rails 在带有静态脚本文件的视图中渲染

Ruby on Rails:将数据调用到 javascript 中的首选方法?

墨者 Ruby On Rails漏洞复现第一题(CVE-2018-3760)

如果 Ruby on Rails 中有设置限制,如何显示特定的 div 元素

墨者靶场 Ruby On Rails漏洞复现第二题(CVE-2019-5418)

墨者靶场 Ruby On Rails漏洞复现第二题(CVE-2019-5418)