[ROR] How to define class method (Howto define class methods in a mixin module) in module mixin

Method a: A method include the modification module

module Bbq
  def self.included(base)
    base.send :include, InstanceMethods
    base.extend ClassMethods
  end

  module InstanceMethods
    def m1
      'instance method'
    end
  end

  module ClassMethods
    def m2
      'this is class method'
    end
  end
end

class Test
  include Bbq
end  

 

test:

irb(main):030:0> Test.m2
=> "this is class method"

irb(main):031:0> Test.m1
Traceback (most recent call last):
NoMethodError (undefined method `m1' for Test:Class)

irb(main):032:0> Test.new.m1
=> "instance method"

  

Method Two: With ActiveSupport :: Concern

require 'active_support/concern'

module Bbq2  extend ActiveSupport::Concern

  def m1
    'instance method'
  end

  class_methods  do
    def m2
      'this is class method'
    end
  end
end

class Test2
  include Bbq2
end  

  

test:

irb(main):019:0> Test2.m2
=> "this is class method"
irb(main):020:0> Test2.m1
Traceback (most recent call last):
NoMethodError (undefined method `m1' for Test2:Class)
irb(main):021:0> Test2.new.m1
=> "instance method"

  

Guess you like

Origin www.cnblogs.com/dajianshi/p/11453543.html