开发者

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?


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.


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


Just put this line in application.rb file

config.autoload_paths += Dir["#{config.root}/lib/**/"]

Edited:

This line is working fine for me. I want to suggest one more thing, ruby 1.8.x is not compatible with rails 3.x. So just update your ruby for version 1.9.2

Following is my POC

In lib folder:
lib/test_lib.rb

module TestLib
 def print_sm
   puts "Hello World in Lib Directory"
 end
end


In model file:

include TestLib
def test_method
  print_sm
end

And In application.rb

config.autoload_paths += Dir["#{config.root}/lib/**/"]


Now you can call test_method like this in controller:

ModelName.new.test_method #####Hello World in Lib Directory

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜