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?
Rake enables you to define a set of tasks and the dependencies between them in a file, and then have the right thing happen when you run any given task. The combination of convenience and flexibility that Rake provides has made it the standard method of job automation for Ruby projects.
Rake is a Make-like program implemented in Ruby. Tasks and dependencies are specified in standard Ruby syntax. Rake has the following features: * Rakefiles (rake's version of Makefiles) are completely defined in standard Ruby syntax. No XML files to edit.
Including => :environment will tell Rake to load full the application environment, giving the relevant task access to things like classes, helpers, etc. Without the :environment , you won't have access to any of those extras.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With