2

I have a gem say 'A' is used in the gem and the gemspec file adds a runtime dependency saying

s.add_dependency 'A', '~> 1.0'

I get an error saying some file/class was not found the in the gem when I run my application. This error goes away when I include the gem in the applications Gemfile.

Why should I need to include the gem in the application despite it being a runtime dependency?

wurde
  • 2,487
  • 2
  • 20
  • 39
Vinay
  • 41
  • 5

1 Answers1

4

This is just how gem dependencies work. When you add a dependency it doesn’t automatically require the depended on gem (in fact it can’t because there is no way of knowing the filename to require — not all gems have the same name as their main file).

Adding a dependency to a gem has two effects. First, when you install the gem the depended on gems are also installed automatically.

Second, when the gem is activated (which normally happens when you require a file from it, but can be done explicitly with gem) the gem’s lib dir is added to the load path, and so are the lib dirs of any dependencies. This ensures that when the main gem calls require on these dependencies the correct version will be used.

The main gem still needs to call require on its dependencies. There is no way in general for Rubygems to know which file from the gem should be required, or when (or even if) it should happen. For example a dependency may only be needed in certain cases, so you want to avoid calling require (which would slow you down) unless you actually needed the functionality provided.

matt
  • 78,533
  • 8
  • 163
  • 197
  • This is kind of confusing . How come we don't require when we add gem dependencies in gemfile . – Vinay Jul 19 '14 at 18:48
  • @Vinay You _do_ need to `require` when using a Gemfile with Bundler, but Bundler provides a `Bundler.require` method as a convenience, which requires all of the gems in your Gemfile. Rails uses this by default (check your `config/application.rb` file if you’re using Rails), so all the dependencies are required when your call `Bundler.require`. (Note that Rubygems and Bundler are separate libraries (at least currently, there is talk Bundler being included in Rubygems in the future)). – matt Jul 19 '14 at 19:27