Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Including rake tasks in gems

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?

like image 482
jsharpe Avatar asked Dec 10 '09 04:12

jsharpe


People also ask

How do you define a rake task?

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.

What is GEM rake?

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.

What is environment rake task?

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.


1 Answers

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.

like image 66
edebill Avatar answered Oct 02 '22 05:10

edebill