Reputation: 2118
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>
Is extend
relevant here ?
Do I use the correct syntax, module and file name ?
Is there something to configure to make sure the lib/module is loaded or is it convention ?
Thanks for your help,
Best regards,
Fred
Upvotes: 1
Views: 100
Reputation: 2118
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
Upvotes: 0
Reputation: 14774
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
Upvotes: 2