Some functionality within my rails application looks better as if it was a separate "module", that should be accessed via require
. For example, assume it's a function to calculate Fibonacci numbers.
The functionality is independent on rails application and can be reused in other projects, so it should not be stored near application controllers and models, I suppose. But since I'm not going to detach it into separate project, thus placing it to vendor
folder seems like not the right thing.
Where should I place it then?
Before Rails 5, the place to put reusable code such as this is in the lib
directory. However you do not need to require
anything as lib
is already in the load path and it's contents will be loaded during initialization.
If you need to extend an existing class, you define your module first and then include it by sending it as a message to the class you wish to extend, e.g.
module MyExtensions
def self.included base
base.instance_eval do
def my_new_method
…
end
end
end
end
ActiveRecord::Base.send :include, MyExtensions
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With