module Test
def self.model_method
puts "this is a module method"
end
end
class A
include Test
end
A.model_method
this will be error with:
undefined method `model_method’ for A:Class (NoMethodError)
But when I use metaclass of A. it works:
module Test
def model_method
puts "this is a module method"
end
end
class A
class << self
include Test
end
end
A.model_method
Can someone explain this?
If you want to have both class methods and instance methods mixed into a class when including a module, you may follow the pattern:
Basically to over-simplify it, you
extendto add class methods and youincludeto add instance methods. When a module is included, it’s#includedmethod is invoked, with the actual class it was included in. From here you canextendthe class with some class methods from another module. This is quite a common pattern.See also: http://api.rubyonrails.org/classes/ActiveSupport/Concern.html