Matthew
Matthew

Reputation: 5825

How do you extend class level methods to a separate module in Rails?

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.

Upvotes: 3

Views: 908

Answers (1)

John Topley
John Topley

Reputation: 115292

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

Upvotes: 4

Related Questions