Requires a gem inside a rake task

I use a jeweler to create a gemstone for Rails 3. The pearl contains a rake task, and one of the things that it does is to clean the database, so I use "database_cleaner".

I indicate the gem dependency inside the gem file gemfile

gem 'database_cleaner' 

And in the rakefile

 Jeweler::Tasks.new do |gem| ... gem.add_dependency 'database_cleaner' end 

Then inside lib I created the files my_gem.rb and tasks.rake. As shown below, 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 gem (sudo rake install), created an empty rails project, and added the gem dependency to the Gemspec rails ( gem 'my_gem' ). But when I try to run rake my_task , I get an uninitialized constant DatabaseCleaner error message.

I also tried adding require 'database_cleaner' from the task, which causes the error no such file to load -- database_cleaner and gem 'database_cleaner' , which causes the database_cleaner is not part of the bundle. Add it to Gemfile. 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 any way to solve this problem without adding gem 'database_cleaner' to rails Gemspec project?

thanks

UPDATE (adding a link to the source code): https://github.com/jordinl/dummy_tasks

+6
ruby ruby-on-rails ruby-on-rails-3 bundler
source share
1 answer

Here is what I did to make this work:

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 adding the database_cleaner gem to the Gemfile application.

+3
source share

All Articles