Write Software, Well

February 03, 2024

What is __FILE__ in Ruby?

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 or module_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.

Subscribe to get future posts via email (or grab the RSS feed)

Comments

No comments yet. Be the first to leave one.

Sign in to leave a comment.