Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot include module in model

I'm using

Ruby version              1.8.7
Rails version             3.0.3

I have a method called alive in every model of my rails app:

  def alive
    where('deleter is null')  
  end   

I don't want to copy this code in every model so I made a /lib/life_control.rb

module LifeControl    
  def alive
    where('deleter is null')  
  end   

  def dead
    where('deleter is not null')  
  end    
end

and in my model (for example client.rb) I wrote:

class Client < ActiveRecord::Base
  include LifeControl   
end

and in my config/enviroment.rb I wrote this line:

require 'lib/life_control'

but now I get a no method error:

NoMethodError in
ClientsController#index

undefined method `alive' for
#<Class:0x10339e938>

app/controllers/clients_controller.rb:10:in
`index'

what am I doing wrong?

like image 853
w1ng Avatar asked Mar 09 '11 10:03

w1ng


People also ask

How to include module in model rails?

You can include a module in a class in your Rails project by using the include keyword followed by the name of your module.

How to use modules in rails?

Creating a module: Writing a module is similar to writing a class, except you start your definition with the module keyword instead of the class keyword. As we can`t instantiate the module so for using the module we need to extend ar include the module into a class. puts “Module Method: Hi there!”


2 Answers

include will treat those methods as instance methods, not class methods. What you want to do is this:

module LifeControl    
  module ClassMethods
    def alive
      where('deleter is null')  
    end   

    def dead
      where('deleter is not null')  
    end    
  end

  def self.included(receiver)
    receiver.extend ClassMethods
  end
end

This way, alive and dead will be available on the class itself, not instances thereof.

like image 150
dnch Avatar answered Oct 06 '22 22:10

dnch


I'm aware this is a pretty old question, the accepted answer did work for me, but that meant me having to re-write a lot of code because i have to change the module to a nested one.

This is what helped me with my situation and should work with most of today's applications.(not sure if it'll work in the ruby/rails version in the question)

instead of doing include use extend

So as per the question, the sample code would look like:

class Client < ActiveRecord::Base
  extend LifeControl   
end
like image 38
Alfie Avatar answered Oct 06 '22 23:10

Alfie