w1ng w1ng - 2 months ago 9
Ruby Question

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?

Answer

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.

Comments