To use self. or not.. in Rails

后端 未结 6 546
长情又很酷
长情又很酷 2020-11-30 21:29

I\'ve been coding in Ruby for sometime now, but I don\'t understand when to use:

def self.METHOD_NAME
end

or just:

def METH         


        
6条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-30 22:13

    A good guide on when to use which one:

    • If the method depends on any internal state of the object, or must know which instance of the object it is addressing, then DO NOT make it a class (self.) method.
    • If the method does not depend on the state of the object, or on having a specific instance of the object, then in may be made a class method.

    When making a class method, think carefully about which class or module it belongs in. If you ever catch yourself duplicating code in class methods across classes, factor it into a module that other classes may mix in.

提交回复
热议问题