【问题标题】:Ruby add lines to block (Proc) of codeRuby 将行添加到代码块 (Proc)
【发布时间】:2012-11-28 12:48:30
【问题描述】:

示例很简单,我需要 Ruby 1.8.7

的解决方案

编辑 添加了Ramaze 调用以更好地解释编辑块的需要。我想要一种更改块的方法,以便我可以包装rescue 块并在线程失败时记录。 APIlink

class Foo
  def self.execute(&block)
    # Remaze will create new thread to execute the block
    # I want to change block so that I can add rescue in case thread fails
    Ramaze::defer(block)
  end
end

用法

Foo.execute do
  puts "Hello!!!"
end
# => Hello!!!

我想要做的是向&block 添加几行代码,例如puts "World!!! 最后但动态。现实世界的实现是我有一个推迟创建线程的类,我想在推迟创建线程之前添加rescue 块。这样我就不需要在线程失败时挠头。

谢谢。

【问题讨论】:

  • 我知道有一个 gem 也可以做到这一点,这也会很有帮助。现在好像找不到了。
  • 您可以将该过程包装在另一个过程中并调用它。
  • 你为什么不只是在调用之后调用 puts 呢?例如def self.execute(&block) block.call; puts "ho"; end 或者将块包装成另一个......
  • 你能修改 Foo.execute 吗?还是您需要覆盖它?
  • 已编辑问题,以便更好地解释我需要编辑块。呵呵想简化一下。

标签: ruby-on-rails ruby metaprogramming


【解决方案1】:

原来解决方案很简单,只是没有使用积木的经验,马上就看到了。 Sergio 建议的东西。

class Foo
  def self.execute(&block)
    Ramaze::defer(&wrap(&block))
  end

  private

  def self.wrap(&block)
    return lambda do
     begin
      yield
      rescue Exception => e
       Log.error "[ERROR IN THREAD] #{e.message}, #{e.backtrace}"
      end
    end
  end
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-24
    • 1970-01-01
    • 2020-03-11
    • 2018-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多