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

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.