简体   繁体   English

在选择语法中使用开始和救援

[英]Use begin and rescue in select syntax

I want to select the task which won't get exception in the following code, How could I get it ? 我想选择以下代码中不会出现异常的task ,我该如何获得它?

if the task status contains the pid and the process is running on my system, then it won't get exception. 如果任务状态包含pid,并且进程正在我的系统上运行,则不会获取异常。

This code is in my helper function, should I move some function to Model ? 这段代码在我的辅助函数中,我应该将某些函数移至Model吗? (I'm using ROR) (我正在使用ROR)

  def sanitize_running_tasks(tasks)

    sanitized_tasks = tasks.select do |task|
      begin
        Process.kill 0, task.status.to_i
      rescue Exception => e
        task.status = :FAIL
        task.save
      end
    end
  end

Please consider putting the kill method on Task. 请考虑在任务上使用kill方法。

  def sanitize_running_tasks(tasks)
    tasks.select &:kill
  end

  class Task
    def kill
      Process.kill 0, status.to_i
      true
    rescue Exception => e
      mark_failed!
      false
    end

    def mark_failed!
      update_attributes status: :FAIL
    end
  end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM