多类的DRY-ing方法抢救

时间:2019-03-09 13:26:23

标签: ruby metaprogramming

我正在尝试做一些对我来说很基础的事情,但我想不出一种使它变干的方法。

这是我最初使用的代码:

我的第一个工人

class WorkerOne < BaseWorker
  def perform
    # do stuff
  rescue *exceptions_to_rescue_with_error => error
    job_error(error, try_later: false)
  rescue *exceptions_to_rescue_with_error_and_try_later => error
    job_error(error, try_later: true)
  rescue *exceptions_to_rescue_with_warning => message
    job_warning(message, try_later: false)
  end
end

第二个工人

class WorkerTwo < BaseWorker
  def perform
    # do stuff
  rescue *exceptions_to_rescue_with_error => error
    job_error(error, try_later: false)
  rescue *exceptions_to_rescue_with_error_and_try_later => error
    job_error(error, try_later: true)
  rescue *exceptions_to_rescue_with_warning => message
    job_warning(message, try_later: false)
  end
end

父类

class BaseWorker
  def exceptions_to_rescue_with_error
    [
      Exceptions::SomeOtherError,
      ActiveRecord::RecordNotFound
    ]
  end

  def exceptions_to_rescue_with_error_and_try_later
    [
      Exceptions::SomeError1,
      Exceptions::SomeError2,
    ]
  end

  def exceptions_to_rescue_with_warning
    [
      Exceptions::SomeWarning
    ]
  end
end

这是我添加到BaseWorker使其工作的方法:


  def self.with_job_rescue_for_perfom
    define_method(:perform) do |*args, &block|
      self.perform(*args, &block)
      rescue *exceptions_to_rescue_with_error => error
        job_error(error, try_later: false)
      rescue *exceptions_to_rescue_with_error_to_try_later => error
        job_error(error, try_later: true)
      rescue *exceptions_to_rescue_with_warning => message
        job_warning(message, try_later: false)
    end
  end
end

我被困在那里,看不到下一步应该去哪里。看来here使用的方法对我不起作用,因为我没有使用模块。

有什么主意吗?

1 个答案:

答案 0 :(得分:0)

我会做类似的事情:

class BaseWorker
  def exceptions_to_rescue_with_error
    [
      Exceptions::SomeOtherError,
      ActiveRecord::RecordNotFound
    ]
  end

  def exceptions_to_rescue_with_error_and_try_later
    [
      Exceptions::SomeError1,
      Exceptions::SomeError2,
    ]
  end

  def exceptions_to_rescue_with_warning
    [
      Exceptions::SomeWarning
    ]
  end

  def perform
    do_stuff
  rescue *exceptions_to_rescue_with_error => error
    job_error(error, try_later: false)
  rescue *exceptions_to_rescue_with_error_and_try_later => error
    job_error(error, try_later: true)
  rescue *exceptions_to_rescue_with_warning => message
    job_warning(message, try_later: false)
  end
end

class WorkerOne < BaseWorker
  def do_stuff
    # do stuff
  end
end

class WorkerTwo < BaseWorker
  def do_stuff
    # do stuff
  end
end