Rails rails 中的 rake 任务,return 报错?

string2020 · 2014年09月24日 · 2397 次阅读

我在 rails 项目里面写了一个任务

namespace :jshop do
  desc '导入excel数据'
  task :import_tourism_rate => :environment do |t|

    res = parse_rate()
    if res == 1
         puts "product=#{pid_hash[pid]} is parse successed . "
        else
         puts "product=#{pid_hash[pid]} is parse failed . "
     return
        end
  end
end

这里面有个 return 我是想当 res!= 1 的时候,就退出任务

但是,报错了。

ly@lypc:~/src/jshop$ rake jshop:import_tourism_rate
product=53fc1b5203af787591000008 is parse failed . 
rake aborted!
LocalJumpError: unexpected return
/home/ly/src/jshop/lib/tasks/import_tourism_rate.rake:39:in `block (3 levels) in <top (required)>'
/home/ly/src/jshop/lib/tasks/import_tourism_rate.rake:18:in `each'
/home/ly/src/jshop/lib/tasks/import_tourism_rate.rake:18:in `block (2 levels) in <top (required)>'
Tasks: TOP => jshop:import_tourism_rate
(See full trace by running task with --trace)

请问,为什么。

A Rake task is basically a block. A block, except lambdas, doesn't support return but you can skip to the next statement using next which in a rake task has the same effect of using return in a method.

task :foo do
  puts "printed"
  next
  puts "never printed"
end

Or you can move the code in a method and use return in the method.

task :foo do
  do_something
end

def do_something
  puts "startd"
  return
  puts "end"
end

I prefer the second choice.

http://stackoverflow.com/questions/2316475/how-do-i-return-early-from-a-rake-task

需要 登录 后方可回复, 如果你还没有账号请 注册新账号