anton evangelatov anton evangelatov - 28 days ago 5x
Ruby Question

How to add "pry" when developing a Ruby gem

I have a gem called "something".

I would like to add pry as a development dependency when developing the gem. However I don't know how to load it.

If I have "require something" inside lib/something.rb , when I release the gem, it throws a LoadError, because pry is only a development dependency.

At the same time I don't want to keep adding and removing pry when I am committing code.

What is the best way to require pry only when developing the application, but not require it as a dependency for the gem?


You can use the add_development_dependency in the gemspec file. You'll still have to require it in your lib/something.rb file within a begin .. rescue LoadError block. (Edit 2, see below)

In your case, it will be something like the following:

spec.add_development_dependency 'pry', '~>'

The purpose of add_development_dependency is to separate the gems into dependencies that get installed when you execute gem install mygem vs development-only dependencies that are installed only when you execute gem install mygem --development.

Edit: @Pierre-Louis Gottfrois' solution

Modify the Gemfile directly and add a test group. This question describes the process. This does not appear to be a preferred solution according to Yehuda Katz.

Edit 2: begin require ... rescue LoadError is apparently a common practice for Ruby scripts, according to this Making Ruby Gems article.