tags:

views:

7617

answers:

5

I see this all the time in ruby:

require File.dirname(__FILE__) + "/../../config/environment"

What I am wondering is what does the __FILE__ mean?

+11  A: 

It is a reference to the current file name so in foo.rb __FILE__ would be interpreted as 'foo.rb'

Edit: removed incorrect assumption that it referenced the full path. It is only a reference to the actual file name only.

Geoff
This answer is not accurate. __FILE__ is the "relative" path to the file from the current execution directory - not absolute. You must use File.expand_path(__FILE__) to get the absolute path
Luke Bayes
Double underscores were automatically removed within the comment above.
Luke Bayes
+2  A: 

http://neeraj.name/blog/articles/228-file-in-ruby

John Boker
article is gone
phoet
+2  A: 

__FILE__ is the filename with extension of the file containing the code being executed.

In foo.rb, __FILE__ would be "foo.rb".

If foo.rb were in the dir /home/josh then File.dirname(__FILE__) would return /home/josh.

Ethan
+3  A: 

in ruby (windows version anyways) I just checked and __FILE__ does not contain the full path to the file, instead it contains the path to the file relative to where its being executed from. in PHP __FILE__ is the full path (which IMO is preferable). This is why in order to make your paths portable in ruby you really need to use this:

File.expand_path(File.dirname(__FILE__) + "relative/path/to/file")

I should note that in ruby 1.9.1 FILE contains the full path to the file, the above description was for when I used ruby 1.8.7.

In order to be compatible with both ruby 1.8.7 and 1.9.1 (not sure about 1.9) you should require files by using the construct I showed above.

Matt Wolfe
+4  A: 

The value of __FILE__ is a relative path that is created and stored (but never updated) when your file is loaded. This means that if you have any calls to Dir.chdir anywhere else in your application, this path will expand incorrectly.

puts __FILE__
Dir.chdir '../../'
puts __FILE__

One workaround to this problem is to store the expanded value of FILE outside of any application code. As long as your require statements are at the top of your definitions (or at least before any calls to Dir.chdir), this value will continue to be useful after changing directories.

$MY_FILE_PATH = File.expand_path(File.dirname(__FILE__))

# open class and do some stuff that changes directory

puts $MY_FILE_PATH
Luke Bayes