Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where should I place my own "module" within rails application?

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?

like image 648
P Shved Avatar asked Feb 04 '23 08:02

P Shved


1 Answers

Rails < 5

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
like image 146
Steve Graham Avatar answered Mar 15 '23 03:03

Steve Graham