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.
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.
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.
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.
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.
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