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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…