Gem dependencies with Rails 3 engine fail in initi

2020-07-17 16:46发布

问题:

tldr; When I run a rake task in a test app which uses an Engine, the Engine dependencies don't seem to be respected. I have to (-D)RY by specifying the dependency in the test app's Gemfile

I've created a Rails Engine as a gem using Jeweler. It has a dependency on Devise which I've specified in the Rakefile:

gem.add_runtime_dependency 'devise', '~> 1.1.3'

In my test app I add the Engine dependency to the Gemfile, and bundle install shows that Devise is picked up and installed. However if I run an initial rake db:migrate an error is thrown:

uninitialized constant Devise
<snip>config/initializers/devise.rb:3

If I manually add the Devise dependency to the test app's Gemfile it works. I've probably missed something obvious, but at this stage it appears the test app picks up and installs the dependency properly, but for some reason the initializer code fails unless the dependency is listed again in the test app's Gemfile.

回答1:

You're likely to have found a solution or a workaround, but I'll put how I solved this in case someone has the same problem.

Just put:

require 'devise'

in lib/my_gem.rb .

Rails autoloads the gems specified in the Gemfile and nothing else. If you're developing a gem that has dependencies, you have to require them manually.