ActiveSupport ::类方法的回调

时间:2012-10-13 05:26:18

标签: ruby-on-rails ruby callback activesupport eigenclass

是否可以在类方法上使用ActiveSupport::Callbacks?更具体地说,在下面的模块中,您将include ActiveSupport::Callbacks放在哪里使define_callbacksrun_callbacks共享相同的状态?

module Handler
  extend ActiveSupport::Concern

  # If you put it here, define_callbacks is defined but run_callbacks is not
  # include ActiveSupport::Callbacks 

  included do
    class_eval do
      define_callbacks :handle
    end
  end

  module ClassMethods
    # If you put it here, run_callbacks is defined but define_callbacks is not
    # include ActiveSupport::Callbacks 

    def handle(task)
      run_callbacks :handle do
        p task
      end
    end
  end
end

class HandlerExample
  include Handler
end

更新

如果有可能,我无法确定,那肯定不是ActiveSupport::Callbacks的设计目的。最好在#handle中创建无状态实例对象。

1 个答案:

答案 0 :(得分:2)

虽然整个想法有点尴尬恕我直言,你已经把define_callbacks放在了错误的地方..你应该把它放在本征类中,例如。

eval<< -EOF      class<<自我define_callbacks ..;    EOF

然后你可以做"发送:extend,ActiveSupport :: Callbacks"。这甚至可能有用。

但我建议您重新考虑它,并采用标准实现,在实例上调用回调。