【问题标题】:Passing a parameter or two to a Rake task将一个或两个参数传递给 Rake 任务
【发布时间】:2011-07-09 14:38:46
【问题描述】:

我有一个要向其传递参数的 rake 任务。例如,我想发出类似的命令

<prompt> rake db:do_something 1

在 rake 任务中:

...
cust = Customer.find( the_id_passed_in )
# do something with this customer record, etc...
...

很简单,对吧?

【问题讨论】:

标签: ruby-on-rails rake


【解决方案1】:

rake 命令接受和定义参数的方式并不漂亮。

这样调用你的任务:

<prompt> rake db:do_something[1,2]

我添加了第二个参数以表明您需要逗号,但请省略任何空格。

并像这样定义它:

task :do_something, :arg1, :arg2 do |t, args|
  args.with_defaults(:arg1 => "default_arg1_value", :arg2 => "default_arg2_value")
  # args[:arg1] and args[:arg2] contain the arg values, subject to the defaults
end

【讨论】:

  • 如何处理需要加载 rails 环境的任务?例如通常task :do_something =&gt; :environment do
  • task :do_something, [:arg1, :arg2] =&gt; :environment do |t, args|
【解决方案2】:

在传递参数时,更好的选择是输入文件,可以是 excel、json 或任何您需要的文件,并从那里读取您需要的数据结构和变量,包括需要的变量名。 读取文件可以有如下结构。

  namespace :name_sapace_task do
    desc "Description task...."
      task :name_task  => :environment do
        data =  ActiveSupport::JSON.decode(File.read(Rails.root+"public/file.json")) if defined?(data)
    # and work whit yoour data, example is data["user_id"]

    end
  end

示例 json

{
  "name_task": "I'm a task",
  "user_id": 389,
  "users_assigned": [389,672,524],
  "task_id": 3
}

执行

rake :name_task 

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-04-08
  • 1970-01-01
  • 2015-02-14
  • 2011-07-02
  • 2012-05-18
  • 2010-10-23
相关资源
最近更新 更多