Inheriting class methods from modules / mixins in Ruby

后端 未结 4 832
鱼传尺愫
鱼传尺愫 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:38

    As Sergio mentioned in comments, for guys who are already in Rails (or don’t mind depending on Active Support), Concern is helpful here:

    require 'active_support/concern'
    
    module Common
      extend ActiveSupport::Concern
    
      def instance_method
        puts "instance method here"
      end
    
      class_methods do
        def class_method
          puts "class method here"
        end
      end
    end
    
    class A
      include Common
    end
    

提交回复
热议问题