Nos*_*mus 54 ruby oop static-methods
我想要一个每5分钟执行一次的方法,我为ruby(cron)实现了.但它不起作用.我认为我的方法无法访问.我想要执行的方法位于一个类中.我想我必须将该方法设为静态,以便我可以访问它MyClass.MyMethod.但我找不到合适的语法,或者我找错了地方.
Schedule.rb
every 5.minutes do
runner "Ping.checkPings"
end
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
Ash*_*ish 93
要声明静态方法,请写...
def self.checkPings
# A static method
end
Run Code Online (Sandbox Code Playgroud)
... 要么 ...
class Myclass extend self
def checkPings
# Its static method
end
end
Run Code Online (Sandbox Code Playgroud)
Sim*_*ker 58
您可以在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"
Run Code Online (Sandbox Code Playgroud)
另请注意,您的方法使用了错误的命名约定.它应该是check_pings,但这不会影响你的代码是否有效,它只是红宝石风格.
ssr*_*sri 13
从中更改您的代码
class MyModel
def checkPings
end
end
Run Code Online (Sandbox Code Playgroud)
至
class MyModel
def self.checkPings
end
end
Run Code Online (Sandbox Code Playgroud)
请注意,方法名称中添加了self.
def checkPings是MyModel类的实例方法,而是def self.checkPings类方法.