views:

52

answers:

3

Hi,

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

+2  A: 

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.

sepp2k
Thank you very much :)
Felix
A: 

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)