Ruby on the Rails - Static Method

I want the method to execute every 5 minutes, I implemented it every time for ruby โ€‹โ€‹(cron). But that does not work. I think my method is not available. The method I want to execute is in the class. I think I need to make this method static so that I can access it using MyClass.MyMethod . But I can not find the correct syntax, or maybe I'm 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 
+52
oop ruby static-methods
Mar 08 '11 at 11:00
source share
5 answers

To declare a static method, write ...

 def self.checkPings # A static method end 

... or...

 class Myclass extend self def checkPings # Its static method end end 
+85
Mar 08 2018-11-11T00:
source share

You can use static methods in Ruby as follows:

 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" 

Also note that you are using the wrong naming convention for your method. It should be check_pings instead, but it doesnโ€™t affect your code or not, itโ€™s just ruby โ€‹โ€‹style.

+56
Mar 08 2018-11-11T00:
source share

Change your code from

 class MyModel def checkPings end end 

to

 class MyModel def self.checkPings end end 

Note that self is appended to the method name.

def checkPings is the instance method for the MyModel class, while def self.checkPings is the class method.

+13
Mar 08 2018-11-11T00:
source share

Instead of extending self for the whole class, you can create a block that extends from itself and define your static methods inside.

you would do something like this:

 class << self #define static methods here end 

So, in your example, you would do something like this:

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

and you can call it like this: Ping.checkPings

+4
Jul 27 '16 at 18:58
source share

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.

Indeed, the term static method is incorrect in any case. A static method is a method that is not associated with any object and which is not sent dynamically (hence the "static"), but these two are largely a definition of what the "method" means. We already have a good name for this design: procedure.

-fourteen
Mar 08 '11 at 17:12
source share



All Articles