2

我想在 Ruby 中编写一个基类,它允许扩展它的类注册回调,就像 ApplicationController 对 before_filter 所做的那样:

class AController < ApplicationController
  before_filter :foo

  def foo

  end
end

我想自己写一些类似于 before_filter 的另一面。

class AClass < MyBase
  register_callback :callback1

  def callback1
    puts "called!"
  end

  def test
    call_me_maybe 5
  end
end

call_me_maybe方法在MyBase类中定义,可能会调用之前注册的回调。MyBase 的实现是什么样的。

4

2 回答 2

1

ActiveSupport提供了一个Callbacks模块:

https://github.com/rails/rails/blob/master/activesupport/lib/active_support/callbacks.rb

您的基类将类似于以下示例active_support/callbacks.rb

class Record
  include ActiveSupport::Callbacks
  define_callbacks :save

  def save
    run_callbacks :save do
      puts "- save"
    end
  end
end

请参阅callbacks.rb完整示例。

于 2012-09-01T01:48:00.387 回答
0

我想出了一个办法send

class MyBase
  def self.register_callback name
    @@callback_name = name
  end

  def call_me_maybe num
    if num > 0
      self.send @@callback_name
    end
  end
end

不确定使用 send 是否出于任何原因不好......似乎应该有另一种方式......

于 2012-09-01T02:45:37.890 回答