Don't Understand Bundler Interaction with Gems

2019-07-12 02:31发布

问题:

I thought I understood how Bundler works with gems, but after something that recently happened, I am not sure I have it right.

I am developing an Rails application. To start off (and just so I would get familiar with the Rails environment which I haven't worked in before), I did not use an IDE. But, because I'm missing out on some of the advantages of an IDE, I just started using RubyMine. As part of the RubyMine setup, it asked to update all my gems for my existing project.

After that, I could not run "rake [anything]". Every time I did, I received an error of:

You have already activated rake 0.9.3.beta.1, but your Gemfile requires rake 0.9.2.2. Using bundle exec may solve this.

I was okay updating to the next version of rake - that wasn't a problem - but I don't understand what happened in the first place. What happened that I "activated" a newer version of rake. Ultimately, I ended up solving the problem by putting

gem 'rake', '0.9.3.beta.1'

in my Gemfile and running

bundle update rake

But, I'm still not sure what happened here. If I was using 9.2.2 before, why did it all of a sudden blow up like that and how can I prevent that in the future?

回答1:

You should really consider installing and using RVM or Rbenv to manage your ruby versions and gemsets. If you go the Rbenv way, the rbenv-gemset plugin can be used to manage gemsets similar to how RVM natively does.

You have already activated rake 0.9.3.beta.1, but your Gemfile requires rake 0.9.2.2. Using bundle exec may solve this.

At some point between your last bundle execution and installing/configuring/running RubyMine you must have installed rake 0.9.3.beta.1. Because you're not managing your gems through gemsets like RVM or Rbenv will do for you, the default version of Rake became 0.9.3.beta.1 instead of the version installed by bundler, 0.9.2.2.

The above error suggests your Gemfile had something like

gem 'rake', '0.9.2.2'

which does not allow the version of rake being used to be anything but 0.9.2.2.

If you do in fact have 0.9.2.2 on your system in addition to the 0.9.3.beta.1 and your Gemfile is configured for 0.9.2.2, instead of running

rake some:task

you can run

bundle exec rake some:task

and bundler will run some:task through the 0.9.2.2 version of rake. Running tasks related to gems found in a Gemfile through bundleer with bundle exec ... is considered good practice regardless of using RVM or Rbenv.

You can read about bundle exec here.



回答2:

If you are using Rubymine, you should configure it to run rake tasks with bundle exec.

Go to: Run -> Edit Configurations -> Defaults -> Rake -> Bundler tab and check "Run the script in context of the bundle (bundle exec)"

Delete all tasks already created and the default will apply the next time you create them again. You can also configure individually each task created.