While reading open source Ruby code, I often come across this mysterious looking __FILE__
variable (among others) that I never bothered to look into. After coming across it umpteenth time this evening, I decided to read up on it and here's everything I learned.
__FILE__
is a magic variable that contains the filename with extension of the current file that's being executed. For example, if you're running code in a file named main.rb
, __FILE__
will return "main.rb"
.
# scratch/main.rb
puts __FILE__ # main.rb
You can use __FILE__
with File.expand_path
to get the absolute path of the current file.
puts File.expand_path __FILE__
# ~/Software/rails/learn/scratch/main.rb
Here're some interesting use cases I found for this variable while browsing the Rails source code.
- Get the name of the current directory
# actionmailbox/lib/action_mailbox/mail_ext.rb
File.expand_path(File.dirname(__FILE__))
- To set the text for error messages in
class_eval
ormodule_eval
functions, which evaluate the given string or block in the context of the module.
class_eval <<-RUBY, __FILE__, __LINE__ + 1
def #{sym}(...)
custom(Mime[:#{sym}], ...)
end
RUBY
module_eval <<-CODE, __FILE__, __LINE__ + 1
def #{option_name}
options[:#{option_name}]
end
def #{option_name}=(value)
options[:#{option_name}] = value
end
CODE
Note: As you might have guessed, the __LINE__
variable returns the current line number.
That's it. I hope you found this short post helpful and you learned something new.
As always, if you have any questions or feedback, didn't understand something, or found a mistake, please leave a comment below or send me an email. I reply to all emails I get from developers, and I look forward to hearing from you.
If you'd like to receive future articles directly in your email, please subscribe to my blog. If you're already a subscriber, thank you.