Class methods in Ruby on Rails 3 — I'm totally lost!

前端 未结 3 1294
死守一世寂寞
死守一世寂寞 2021-02-10 12:40

Background here.

In the above link, the following example is given:

class << self
  def by_author(author)
    where(:author_id => author.id)
  end         


        
3条回答
  •  不要未来只要你来
    2021-02-10 13:37

    Having class << self is also another way to define your methods so that you do not have to call "def self.my_method" or "def MyClass.my_method" for every single method that you are defining as a class method. Instead of calling

      def self.my_method1
      end
    
      def self.my_method2
      end
    
    class << self
      def my_method1
      end
    
      def my_method2
      end
    end
    

    Cheers!

提交回复
热议问题