-1

I can't require third party code in my .gemspec file. I would like to require a semver library to manage my version number. Why can't I require gems inside my .gemspec?

I have a workaround for my particular problem. What I am interested in the specific reason I can't require code from inside a gemspec. I feel like I am missing something about how Rubygems work. Thanks!

lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'semver'

Gem::Specification.new do |spec|
  spec.add_dependency "semver2", "~> 3.4.2"
  spec.version       = SemVer.find.to_s[1..-1]
end

Running bundle install results in the following error:

$ bundle

[!] There was an error parsing `Gemfile`: There was a LoadError while loading example.gemspec: 
cannot load such file -- semver from
  /opt/pose/auto/stack-overflow/example/example.gemspec:3:in `<main>'

Obviously there is some point before which you cannot depend on 3rd party gems to be on your LOAD_PATH. I am asking for an explanation of where that point is. My guess is because my Gemfile references my gemspec and Bundler had not loaded all the dependencies yet, but that is a guess.

JohnIV
  • 179
  • 1
  • 10
  • 1
    What do you mean by “require code”? Sources? Because to require 3rd party gems is likely the main and only goal of `.gemspec`. – Aleksei Matiushkin Feb 10 '16 at 06:43
  • 1
    Are you confusing declaring dependencies and actually requiring code? – Jesper Feb 10 '16 at 07:17
  • Similar question - https://stackoverflow.com/questions/51564195/how-can-i-install-a-gem-via-bundler-using-gemspec-before-parsing-the-gemspec – jessebs Aug 06 '18 at 19:28

1 Answers1

1

A .gemspec is just a Ruby script like any other Ruby script. Basically the only thing that is "special" is that it is run in an environment where certain libraries have already been required, such as rubygems/specification.

requireing libraries works just like in any other Ruby script.

Jörg W Mittag
  • 363,080
  • 75
  • 446
  • 653
  • You're right that `require` works. My question has been revised to emphasize that, in the gemspec file, you cannot depend on those gems to be on the load path, or even installed. – JohnIV Feb 10 '16 at 17:23