包括在宝石中的耙子任务 [英] including rake tasks in gems
问题描述
2)在环境中配置gem后,如何让它们可用?
在Rails 3上,你通过Railties来完成。下面是为我创建的宝石所做的代码: class BackupTask< Rails :: Railtie
rake_tasks do
Dir [File.join(File.dirname(__ FILE __),'tasks / *。rake')]。each {| f | load f}
end
end
所以你基本上创建一个继承来自Rails :: Railtie,然后在这个类中你有一个rake_tasks块来加载相关的文件。如果你想使用.rake扩展名,你必须加载而不是require。
我发现我需要指定Dir的完整路径(因此File.join体操)。如果我只是想明确列出这个文件,那么我可以说只是说加载任务/ foo.rake',因为我的宝石的lib目录位于加载路径中。
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?
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.
这篇关于包括在宝石中的耙子任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!