方法一: 修改模块的include方法
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
测试:
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"
方法二:借助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
测试:
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"