Posted almost 6 years ago. Visible to the public. Repeats.

Ruby: __FILE__, __dir__ and symlinks

Ruby's __FILE__ keyword returns the path to the current file. On popular for this are Ruby binaries:

Copy
#!/usr/bin/env ruby $LOAD_PATH << File.expand_path('../../lib', __FILE__) require 'my_cli' MyCli.run!

However, if you create a symlink to this file, this will no longer work. __FILE__ will resolve to the path of the symlink, not to its target.

One solution is to use File.realpath(__FILE__).

In Ruby 2+ you can also use this:

Copy
$LOAD_PATH << File.expand_path('../lib', __dir__)

__dir__ is simply a shortcut for File.dirname(File.realpath(__FILE__)).

Does your version of Ruby on Rails still receive security updates?
Rails LTS provides security patches for unsupported versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2).

Owner of this card:

Avatar
Tobias Kraze
Last edit:
almost 4 years ago
by Tobias Kraze
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Tobias Kraze to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more