1

Reading around, I get confused about the right way to load and include a module in Rails 4. I'd like to include this module in several models of my application:

module SimpleSearch
  def self.search(filter)
    if filter.present?
      where('name like ?', "%#{filter}%")
    else
      where('TRUE')
    end
  end
end

The file path is lib/simple_search.rb Thanks to Michael's suggestion, I updated the config/application.rb to help loading the module (question 3 is solved):

config.autoload_paths += %W(#{config.root}/lib)

In the model, I include:

class BusinessRule < ActiveRecord::Base
extend SimpleSearch

and get a new error at execution:

undefined method `search' for #<ActiveRecord::Relation::ActiveRecord_Relation_BusinessRule:0x00000003670770>
  1. Is extend relevant here ?

  2. Do I use the correct syntax, module and file name ?

  3. Is there something to configure to make sure the lib/module is loaded or is it convention ?

Thanks for your help,

Best regards,

Fred

user1185081
  • 1,898
  • 2
  • 21
  • 46

2 Answers2

2

Try adding this into the class definition in config/application.rb

config.autoload_paths += %W(#{config.root}/lib)

Taken from here: Rails 4 uninitialized constant for module

Community
  • 1
  • 1
Michael Giovanni Pumo
  • 14,338
  • 18
  • 91
  • 140
0

As far as I understood, the search function is a class function, so it is relevant to include it using extend.

Then, the module definition should not refer to self.

Here is the code update that works fine:

module SimpleSearch
  def search(filter)
    if filter.present?
      where('name like ?', "%#{filter}%")
    else
      where('TRUE')
    end
  end
end

Your observations are welcome,

Best regards,

Fred

user1185081
  • 1,898
  • 2
  • 21
  • 46