Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When and where do I require files in a rails application?

Let's say I have I have the following file in my lib directory of my rails application:

#lib/proxy.rb module SomeService   class ServiceProxy     def do_something     end   end end 

If I want to use ServiceProxy in a model, I can use it like so:

#app/models/product.rb require 'proxy'  class Product < ActiveRecord::Base   def do_something     proxy = SomeService::ServiceProxy.new     proxy.do_something   end end 

This works, but I noticed if I want to use ServiceProxy in another model, I do not need "require 'proxy'" in the second model file. It seems having "require 'proxy'" once in any model will add it to the lookup path.

Can someone explain this behavior and the best practice surrounding it in a rails app?

Thanks!

UPDATE: Based on floyd's answer below, if my ServiceProxy file was saved as so,

#lib/some_service/service_proxy.rb 

then I would not have to explicitly require the file.

like image 523
Lee Avatar asked Jan 22 '10 21:01

Lee


People also ask

What does require do in Rails?

require can also be used to load only a part of a gem, like an extension to it. Then it is of course required where the configuration is. You might be concerned if you work in a multi-threaded environment, as they are some problems with that. You must then ensure everything is loaded before having your threads running.

What is require in Ruby on Rails?

In Ruby to reuse any existing files and modules we can use the require statement, required to allow us to make available the submodules inside our codes, there are two way to require any file first way by giving the full path of the file like require './dire/lib/xyz.

What is the purpose of environment RB and application RB files?

In the environment. rb file you configure these run-levels. For example, you could use it to have some special settings for your development stage, which are usefull for debugging. The purpose of this file is to configure things for the whole application like encoding.


1 Answers

This is a helpful post about this issue.

In short, Rails autoloads classes in your lib directory only if they follow the proper naming conventions.

like image 85
tfwright Avatar answered Oct 13 '22 16:10

tfwright