Nice programing

Ruby on Rails-정적 메서드

nicepro 2021. 1. 9. 11:38
반응형

Ruby on Rails-정적 메서드


5 분마다 메서드를 실행하고 싶습니다. 루비 (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

정적 메서드를 선언하려면 ...

def self.checkPings
  # A static method
end

... 또는 ...

class Myclass extend self

  def checkPings
    # Its static method
  end

end

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대신 해야 하지만 이것은 코드가 작동하는지 여부에 영향을 미치지 않으며 단지 루비 스타일 일뿐입니다.


코드 변경

class MyModel
  def checkPings
  end
end

...에

class MyModel
  def self.checkPings
  end
end

메소드 이름에 self가 추가됩니다.

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


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


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.

ReferenceURL : https://stackoverflow.com/questions/5231534/ruby-on-rails-static-method

반응형