felix
felix

Reputation: 11552

Ruby Module Include Question

I have a CommonFunctions Module inside the lib/ folder. I have a Question Model, which includes the CommonFunctions module. Now I am trying to access the favorite function of the CommonFunctions like Question.favorite. But I am getting NoMethodError. I have included the code. Can anyone please tell me where I am doing the mistake

Error

NoMethodError: undefined method `favorite' for Class:0x00000100e11508

Inside lib/CommonFunctions.rb

module CommonFunctions
  def favorite(object_id)
  end
end

Inside app/models/Question.rb

require 'lib/CommonFunctions.rb'
class Question
  extend CommonFunctions
end

I am executing the following code from the script/console

   Question.favorite(1)

Thanks


This was a duplicate of How do I properly include a module and call module functions from my Rails model?

Upvotes: 0

Views: 537

Answers (2)

user425270
user425270

Reputation: 83

The module method is an instance method when you want it to be a class method. Use the code below instead

module CommonFunctions   
  def self.favorite(object_id)   
  end 
end

Using the word "self" defines the method as a class method (or static)

Upvotes: 1

sepp2k
sepp2k

Reputation: 370425

Your code is correct. Make sure you have the current version of the classes loaded in the console (try reload!).

As a sidenote: if you rename CommonFunctions.rb to common_functions.rb, it will be autoloaded by rails and you don't need the require.

Upvotes: 2

Related Questions