简体   繁体   中英

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 ?

if the task status contains the pid and the process is running on my system, then it won't get exception.

This code is in my helper function, should I move some function to Model ? (I'm using 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.

  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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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