Ruby方法作为块

时间:2014-10-14 12:15:55

标签: ruby-on-rails callback event-handling

目前我的Rails应用程序中有一个类将块调用为事件处理程序(回调):

class MyClass
  #Event handler hooks:

  def on_event1(&block)
    @on_event1 = block
  end

  def on_event2(&block)
    @on_event2 = block
  end

  #Event triggers:

  def do_event1
    @on_event1.call if @on_event1
  end

  def do_event2
    @on_event2.call if @on_event2
  end
end

初​​始化器:

mc = MyClass.new

#===== Event handlers: =====

mc.on_event1 do
  #do some stuff
end

mc.on_event2 do
  #do some stuff
end

我想将事件处理程序放入单独的类中,将它们从块转换为方法:

class MyClassHandlers
   def self.event1_handler
     #do some stuff
   end

   def self.event2_handler
     #do some stuff
   end
end

如何在应该给出块的地方调用方法?

我希望将事件绑定视为:

mc = MyClass.new
mc.on_event1 = MyClassHandlers.event1_handler
mc.on_event2 = MyClassHandlers.event2_handler

1 个答案:

答案 0 :(得分:1)

你可以使用lambdas:

mc = MyClass.new
mc.on_event1 = lambda { MyClassHandlers.event1_handler } 
mc.on_event2 = lambda { MyClassHandlers.event2_handler }