How to add “pry” when developing a Ruby gem

独自空忆成欢 提交于 2019-12-10 04:28:34

问题


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?


回答1:


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', '~> 0.9.12.2'

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.




回答2:


I think I found a workaround for that. If you configure bundler to use pry as your console with

$ bundle config console pry

Then pry is itself required and you don't need to explicitly require in your source files.
Plus, you get a history on pressing ' ↑ '.



来源:https://stackoverflow.com/questions/18335229/how-to-add-pry-when-developing-a-ruby-gem

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!