Ruby on rails - Static method

2019-01-17 18:53发布

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

5条回答
Summer. ? 凉城
2楼-- · 2019-01-17 19:23

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.

查看更多
我想做一个坏孩纸
3楼-- · 2019-01-17 19:34

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 :

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 as follows : Ping.checkPings

查看更多
一夜七次
4楼-- · 2019-01-17 19:43

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
查看更多
仙女界的扛把子
5楼-- · 2019-01-17 19:47

Change your code from

class MyModel
  def checkPings
  end
end

to

class MyModel
  def self.checkPings
  end
end

Note there is self added to the method name.

def checkPings is an instance method for the class MyModel whereas def self.checkPings is a class method.

查看更多
我想做一个坏孩纸
6楼-- · 2019-01-17 19:48

You can use static methods in Ruby like this:

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 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.

查看更多
登录 后发表回答