daremkd
daremkd

Reputation: 8424

Why is .gemspec using so complicated code to get the lib directory (Ruby)?

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?

Upvotes: 2

Views: 344

Answers (2)

sawa
sawa

Reputation: 168229

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.

Upvotes: 2

Jed Schneider
Jed Schneider

Reputation: 14671

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

Upvotes: 0

Related Questions