Read more

Ruby: __FILE__, __dir__ and symlinks

Tobias Kraze
August 23, 2016Software engineer at makandra GmbH

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

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

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

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:

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

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

Posted by Tobias Kraze to makandra dev (2016-08-23 14:50)