2

I've tried to create a Ruby gem by doing 'bundle gem [gem_name]' and all went well (there is a main folder and inside there is lib and spec folders). In the .gemspec file I saw this:

lib = File.expand_path('../lib', __FILE__)

while produces an absolute path to the /lib. However, the same result can be accomplished with:

File.expand_path('lib')

There was some explanation in this post File.expand_path("../../Gemfile", __FILE__) How does this work? Where is the file? on how complicated the first approach is, so I was wondering, does it really have an advantage relative to the second and simpler approach?

Community
  • 1
  • 1
daremkd
  • 8,244
  • 6
  • 40
  • 66
  • I think the odd, but often-used idiom in your first code fragment is one of the reasons why `__dir__` was added in Ruby 2.0.0. Your two code fragments are not equivalent, the second one does not use the current file path. – Neil Slater Jan 03 '14 at 13:24

2 Answers2

2

File.expand_path assumes Dir.getwd as the default reference point, which is not necessarily the same as "#{__FILE__}/.." (or Ruby 2.0's __dir__).

Since Ruby 2.0, you can write:

lib = File.expand_path('lib', __dir__)

which is better than the original.

sawa
  • 165,429
  • 45
  • 277
  • 381
0

as long as you are intending for your destination filepath string to be the current working directory, Ruby defaults that second parameter for you. If for some reason you'd want to create an absolute path to another location, you can pass the second parameter:

source: http://ruby-doc.org/core-1.9.3/File.html#method-c-expand_path

Jed Schneider
  • 14,085
  • 4
  • 35
  • 46