views:

77

answers:

1

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.

+3  A: 

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
John Topley
John: you might want to edit your example so that it includes the full code sample and your change (with the changes in bold)
berlin.ab
Good idea - done.
John Topley
Once I saw that you declared the methods as instance methods, it immediately clicked. Thanks!
Matt