Currently there is a class in my Rails application which calls blocks as event handlers (callbacks):
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
Initializer:
mc = MyClass.new
#===== Event handlers: =====
mc.on_event1 do
#do some stuff
end
mc.on_event2 do
#do some stuff
end
I would like to put event handlers into separate class transforming them from blocks to methods:
class MyClassHandlers
def self.event1_handler
#do some stuff
end
def self.event2_handler
#do some stuff
end
end
How to call a method in a place where block should be given?
I would like to see event binding as something like:
mc = MyClass.new
mc.on_event1 = MyClassHandlers.event1_handler
mc.on_event2 = MyClassHandlers.event2_handler
You could use lambdas:
mc = MyClass.new
mc.on_event1 = lambda { MyClassHandlers.event1_handler }
mc.on_event2 = lambda { MyClassHandlers.event2_handler }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.