What "requires" File.expand_path ("../../config/environment", __FILE__) "to do something for sure?

While trying to understand Ruby at a deeper level and deconstructing a boiler room rail application, it seemed like a good way to understand some of the subtleties and elegance of writing a Ruby application that spans different files and directories.

In my current application, dependency on โ€œrequirementsโ€ between files becomes a little problematic (I find that I need to do things like requires '../../../lib/helper' and getting it a little ugly.

I noticed that rail applications do not seem to suffer from this.

I noticed a line:

 require File.expand_path('../../config/environment', __FILE__) 

And when I'm on Google, I find a lot of explanation about the routine Rails program, etc., but there is no clear description of what exactly this line does exactly.

In my travels, I also walked along this line:

 $:.push File.join(File.dirname(__FILE__)) 

I was wondering, somehow this could be a potential solution to my problem. Can someone explain what they are doing for sure?

+8
ruby ruby-on-rails
source share
2 answers

__FILE__ is the relative path to the file from the current directory. File.expand_path will give you the absolute path to the file, so the environment.rb file is required above in your question. $: contains an array of the desired path, so $:.push add the specified path to the list of the desired path so that you can require this file in your application. Rails runs various files at boot time.

+7
source share

File.expand_path('../../config/environment', __FILE__) returns the absolute path to the environment.rb file, which is located in the 'config' directory, which is two levels below the file containing this code.

require then gives you access to the ruby โ€‹โ€‹code defined in the .rb file environment.

0
source share

All Articles