在 gems 中包含 rake 任务 [英] Including rake tasks in gems

查看:11
本文介绍了在 gems 中包含 rake 任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

1) 在 gems 中是否有一个最好"的地方来执行 rake 任务?我在 /tasks/lib/tasks 中看到过它们,并且看到过它们写成 *.rb*.rake -- 不确定哪个(如果有)是正确的"

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) 在环境中配置 gem 后,如何使它们对应用程序可用?

2) How do I make them available to the app once the gem is configured in the environment?

推荐答案

在 Rails 3 上,您可以通过 Railties 完成此操作.这是我刚刚制作的 gem 的代码:

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

所以你基本上创建了一个继承自 Rails::Railtie 的类,然后在该类中你有一个 rake_tasks 块来加载相关文件.如果你想使用 .rake 扩展,你必须加载而不是 require.

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.

我发现我需要指定 Dir 的完整路径(因此是 File.join 体操).如果我只是想明确列出文件,那么我可以只说 load 'tasks/foo.rake' 因为我的 gem 的 /lib 目录在加载路径.

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.

这篇关于在 gems 中包含 rake 任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆