Ruby on Rails - 静态方法
我想要一个每 5 分钟执行一次的方法,我为 ruby (cron) 实现了每当。但这不起作用。我认为我的方法无法访问。 我要执行的方法位于一个类中。我想我必须将该方法设为静态,以便我可以使用 MyClass.MyMethod 访问它。但我找不到正确的语法,或者也许我找错了地方。
时间表.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
I want a method to be executed every 5 minutes, I implemented whenever for ruby (cron). But it does not work. I think my method is not accessible.
The method I want to execute is located in a class. I think I have to make that method static so I can access it with MyClass.MyMethod
. But I can not find the right syntax or maybe I am looking in the wrong place.
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
要声明静态方法,请编写 ...
... 或 ...
To declare a static method, write ...
... or ...
您可以像这样在 Ruby 中使用静态方法:
另请注意,您为方法使用了错误的命名约定。它应该是
check_pings
,但这并不影响你的代码是否有效,它只是 ruby 风格的。You can use static methods in Ruby like this:
Also notice that you're using a wrong naming convention for your method. It should be
check_pings
instead, but this does not affect if your code works or not, it's just the ruby-style.将代码从 更改
为
注意,方法名称中添加了 self。
def checkPings
是类 MyModel 的实例方法,而def self.checkPings
是一个类方法。Change your code from
to
Note there is self added to the method name.
def checkPings
is an instance method for the class MyModel whereasdef self.checkPings
is a class method.您可以创建一个从 self 扩展的块并在其中定义静态方法,而不是为整个类扩展 self 。
你会做这样的事情:
所以在你的例子中,你会做这样的事情:
你可以按如下方式调用它:
Ping.checkPings
Instead of extending
self
for the whole class, you can create a block that extends from self and define your static methods inside.you would do something like this :
So in your example, you would do something like this :
and you can call it as follows :
Ping.checkPings
有一些方法可以在 RoR 中声明静态方法。
#1
#2
There are some ways to declare a static method in RoR.
#1
#2
Ruby 中不能有静态方法。在 Ruby 中,所有方法都是动态的。 Ruby 中只有一种方法:动态实例方法。
事实上,术语“静态方法”无论如何都是用词不当。静态方法是一种不与任何对象关联并且不动态分派的方法(因此是“静态”),但这两个几乎是“方法”的定义。 ”。我们已经为这个构造起了一个完美的名字:过程。
You cannot have static methods in Ruby. In Ruby, all methods are dynamic. There is only one kind of method in Ruby: dynamic instance methods.
Really, the term static method is a misnomer anyway. A static method is a method which is not associated with any object and which is not dispatched dynamically (hence "static"), but those two are pretty much the definition of what it means to be a "method". We already have a perfectly good name for this construct: a procedure.