Given a situation such as:
module Extension
def self.included(recipient)
recipient.extend(ModelClassMethods)
end
module ModelClassMethods
def self.msg
puts 'Hi from module'
end
end
end
class B
include Extension
end
Why is B.msg not available?
>> B.msg
NoMethodError: undefined method `msg' for B:Class
from (irb):16
Am I thinking about this the wrong way? It doesn't seem like this should be all that difficult to accomplish.
The msg
method within your ModelClassMethods
module should be declared as an instance method and not a class method because the act of extending the recipient class already makes it a class method. So:
module Extension
def self.included(recipient)
recipient.extend(ModelClassMethods)
end
module ModelClassMethods
def msg # Note lack of 'self.'
puts 'Hi from module'
end
end
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.