Including rake tasks in gems

后端 未结 3 464
终归单人心
终归单人心 2020-12-13 05:54

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

3条回答
  •  情深已故
    2020-12-13 06:09

    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.

提交回复
热议问题