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

前端 未结 3 1225
死守一世寂寞
死守一世寂寞 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:13

    The following two bits of code are equivalent.

    Using self.method:

    class Hello
      def self.world
        puts "Hello, World!"
      end
    end
    

    Using class << self:

    class Hello
      class << self
        def world
          puts "Hello, World!"
        end
      end
    end
    

    The only difference is readability, as well as the ease in refactoring. The class << self technique is often used when metaprogramming.

    There is another thread that explains this. class << self vs self.method with Ruby: what's better?

提交回复
热议问题