Rails 项目中的耙子范围? [英] Scope of rakes in a rails project?

查看:37
本文介绍了Rails 项目中的耙子范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我正在处理的项目中,我有许多使用 rakes 运行的解析器.当使用另一个 rake 中已经存在的方法名称时,由于它们都使用相同的环境,我会遇到冲突.

I have a number of parsers I run with rakes in a project I'm working on. When using a method name that already exists in another rake, and because they both use the same environment, I get a conflict.

有没有办法限制 rake 文件在其命名空间内的范围?我认为这就是命名空间的全部意义所在?

Is there a way to limit the scope of rake files within their namespace? I thought that was the whole point of the namespace?

示例:

namespace :test do
  task :test_task => :environment do
      ...
  end

  def test_method(argument)
    ...
  end    
end

namespace :other_test do
  task :test_task => :environment do
    ...
  end

  def test_method(argument, argument2)
    ...
  end
end

在这种情况下,当运行 rake test:test_task 时,我会收到无效数量的参数错误.另一方面,如果我在任务本身中定义方法,我必须将方法按顺序保留在 rake 文件的顶部.这有点令人困惑和丑陋.

In this case, when running rake test:test_task I'll receive an invalid amount of arguments error. On the other hand, if I define the method within the task itself, I have to keep the method at the top of the rake file in order. This gets kind of confusing and ugly.

这只是一种必要的邪恶吗?

Is that just a necessary evil?

谢谢!

推荐答案

我认为 rake 任务的命名空间与文件系统中的目录具有相同的用途:它们是关于组织而不是封装.这就是为什么数据库任务在 db: 中,Rails 任务在 rails: 中,等等.

I see the namespaces for rake tasks as serving the same purpose as directories in a file system: they're about organization rather than encapsulation. That's why database tasks are in db:, Rails tasks in rails:, etc.

Rake 命名空间不是类,因此当您在 Rake 命名空间中定义它时,您需要问自己要将 test_method 添加到哪个类.答案是对象.所以,当你完成第二个任务时,Object 已经有一个 test_method 方法,它接受一个参数,Ruby 正确地抱怨.

Rake namespaces are not classes so you need to ask yourself what class you're adding test_method to when you define it within a Rake namespace. The answer is Object. So, when you hit your second task, Object already has a test_method method that takes one parameter and Ruby rightly complains.

最好的解决方案是让你的 Rake 任务非常精简(就像控制器一样),并将任何支持方法(例如 test_method)放在某个库文件中的某个位置.Rake 任务通常应该只做一些设置,然后调用库方法来完成实际工作(即与控制器相同的总体布局).

The best solution is to make your Rake tasks very thin (just like controllers) and put any supporting methods (such as test_method) off in some library file somewhere sensible. A Rake task should usually just do a bit of set up and then call a library method to do the real work (i.e. the same general layout as a controller).

执行摘要:将所有真正的工作和繁重的工作放在您的库文件中,并使您的 Rake 任务为您的库打包.这应该可以通过适当的代码组织解决您的问题.

Executive summary: put all the real work and heavy lifting somewhere in your library files and make your Rake tasks thin wrappers for your libraries. This should make your problem go away through proper code organization.

这篇关于Rails 项目中的耙子范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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