简体   繁体   中英

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?

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, eg

module MyExtensions
  def self.included base
    base.instance_eval do
      def my_new_method
        …
      end
    end
  end
end

ActiveRecord::Base.send :include, MyExtensions

I'll often put stuff in lib , it turns out that anything under lib is in the load path and doesn't need to be require d at all.

edit: After Steve's comment, removed the bit about having to require the files. Also, removed a couple requires from some of my code :P

There is a lib directory in RoR projects which fits well for that purpose - I place common bits of code in form of "libraries" there. Anything from extending ActiveRecord classes to reusable utility methods.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM