Inheriting class methods from modules / mixins in Ruby

后端 未结 4 826
鱼传尺愫
鱼传尺愫 2020-12-04 06:12

It is known that in Ruby, class methods get inherited:

class P
  def self.mm; puts \'abc\' end
end
class Q < P; end
Q.mm # works

However

4条回答
  •  自闭症患者
    2020-12-04 06:40

    A common idiom is to use included hook and inject class methods from there.

    module Foo
      def self.included base
        base.send :include, InstanceMethods
        base.extend ClassMethods
      end
    
      module InstanceMethods
        def bar1
          'bar1'
        end
      end
    
      module ClassMethods
        def bar2
          'bar2'
        end
      end
    end
    
    class Test
      include Foo
    end
    
    Test.new.bar1 # => "bar1"
    Test.bar2 # => "bar2"
    

提交回复
热议问题