Requiring a gem inside a gem's rake task
I'm using jeweler to create a gem for Rails 3. The gem contains a rake task and one of the things it does is wiping the DB, so I'm using 'database_cleaner'.
I'm specifying the gem dependency inside the gem's Gemfile
gem 'database_cleaner'
And in the Rakefile
Jeweler::Tasks.new do |gem|
  ...
  gem.add_dependency 'database_cleaner'
end
Then inside lib I've created the files my_gem.rb and tasks.rake. As follows, my_gem.rb:
module MyGem
  class Railtie < Rails::Railtie
    rake_tasks do
      load 'tasks.rake'
    end
  end
end
And tasks.rake:
task :my_task do
  DatabaseCleaner.strategy = :truncation
  DatabaseCleaner.clean
end
 I installed the gem (sudo rake install), created an empty rails project and added the gem dependency in the rails' Gemspec ( gem 'my_gem' ).  But when I try to run rake my_task I get the error uninitialized constant DatabaseCleaner .  
 I've also tried adding require 'database_cleaner' from inside the task, which raises the error no such file to load -- database_cleaner and gem 'database_cleaner' that raises the error database_cleaner is not part of the bundle. Add it to Gemfile.  database_cleaner is not part of the bundle. Add it to Gemfile. .  
 Is there a way to solve this without adding gem 'database_cleaner' to the rails project's Gemspec?  
Thanks
UPDATE (adding the link to the source code): https://github.com/jordinl/dummy_tasks
Here is what I did to make it work:
https://github.com/johnmcaliley/dummy_tasks/commits/master
tasks.rake
require 'database_cleaner'
require 'dummy_tasks'
namespace :db do
  task :dummy => :environment do
    DatabaseCleaner.strategy = :truncation
    DatabaseCleaner.clean                                             
    Rake::Task['db:seed'].invoke    
  end
end
There may be a more elegant way to do this, but this should at least prevent you from having to add the database_cleaner gem to the app Gemfile
链接地址: http://www.djcxy.com/p/81128.html下一篇: 在宝石的耙子任务中需要一颗宝石
