Including rake tasks in gems

jsharpe picture jsharpe · Dec 10, 2009 · Viewed 17.2k times · Source

1) Is there a 'best' place for rake tasks inside of gems? I've seen them in /tasks, /lib/tasks, and I've seen them written as *.rb and *.rake -- not sure which (if any) is 'correct'

2) How do I make them available to the app once the gem is configured in the environment?

Answer

edebill picture edebill · Mar 26, 2011

On Rails 3, you do this via Railties. Here's the code to do it for a gem I just made:

class BackupTask < Rails::Railtie
  rake_tasks do
    Dir[File.join(File.dirname(__FILE__),'tasks/*.rake')].each { |f| load f }
  end
end

So you basically create a class that inherits from Rails::Railtie, then within that class you have a rake_tasks block that loads the relevant files. You must load instead of require if you want to use a .rake extension.

I found that I need to specify the full path to Dir (hence the File.join gymnastics). If I just wanted to list the file explicitly then I could get away with just saying load 'tasks/foo.rake' because the /lib dir of my gem was in the load path.