Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What Does "require File.expand_path('../../config/environment', __FILE__)" do Exactly?

I've been trying to understand Ruby on a deeper level, and deconstructing a boiler-plate rails app, seemed like a good way to understand some of the niceties and elegance of writing a Ruby app that spans different files and directories.

In my current app, the dependency on the 'requires' between files is becomming slightly problematic (I'm finding I need to do things like requires '../../../lib/helper' and its getting a bit ugly.

I noticed that rails apps don't seem to suffer from this.

I did notice the line:

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

And when I Google it I find lots of explanation about the Rails boot-up routine, etc, but no clear description about what that line DOES exactly.

In my travels, I've also come along this line:

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

I've been wondering if somehow these might be a potential solution to my problem. Can anyone please explain what they do exactly?

like image 937
Ash Avatar asked Apr 07 '14 08:04

Ash


2 Answers

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

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

like image 152
Dragan Nikolic Avatar answered Nov 12 '22 03:11

Dragan Nikolic


__FILE__ is the relative path to the file from current directory. File.expand_path will get you absolute path of file, so above in your question require the environment.rb file. $: contains the array of required path, so $:.push append the your given path into list of required path, so that you can require that file in your app. Rails push various file while booting process.

like image 7
Sanjiv Avatar answered Nov 12 '22 03:11

Sanjiv