require file in rails environment

There are different ways to load particular file in rails application environment if the required file exists.
1. Using RAILS_ROOT

if File.exists?(file=File.join(RAILS_ROOT,’config’, ‘initializers’, ‘smtp_gmail.rb’))

require file

end

2. Using Rails.root & join

require Rails.root.join(‘config’, ‘initializers’, ‘smtp_gmail.rb’)

3. Using Rails.root, join & exists? method.

if File.exists?(file = Rails.root.join(‘config’, ‘initializers’,’smtp_gmail.rb’))

require file

end

4. Using File and direct path to file

require  File.join(‘root’,’app’,’config’, ‘initializers’, ‘smtp_gmail.rb’)

Among all above methods of  loading file, Using Rails.root, join & exists? method seems to be pretty good to have.
Any improvements are most welcome!

Advertisements

About sandipransing

Web Developer #ruby #rails #JS
This entry was posted in Ruby on Rails and tagged . Bookmark the permalink.

2 Responses to require file in rails environment

  1. Satish says:

    * no need to require files from initializers
    * example 3 will not work (undefined method file)
    * example4: do you have “root/app/config/initializers/…” type of path in Rails

    USELESS POST

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s