我有Model
,method_1
到method_10
。我也有ModelObserver
。
在将method1调用ModelObserver
之前,我想通知method_9
,而不是method_10
。
是否有一种干嘛的方式来写这个,而不是在所有9种方法中重复notify_observers(:after_something)?
答案 0 :(得分:8)
在monkey_patches.rb
dirctory中添加名为config/initializers
的文件。
class Object
def self.method_hook(*args)
options = args.extract_options!
return unless (options[:before].present? or options[:after].present?)
args.each do |method_name|
old_method = instance_method(method_name) rescue next
define_method(method_name) do |*args|
# invoke before callback
if options[:before].present?
options[:before].is_a?(Proc) ? options[:before].call(method_name, self):
send(options[:before], method_name)
end
# you can modify the code to call after callback
# only when the old method returns true etc..
old_method.bind(self).call(*args)
# invoke after callback
if options[:after].present?
options[:after].is_a?(Proc) ? options[:after].call(method_name, self):
send(options[:after], method_name)
end
end
end
end
end
该补丁使您可以在类的实例方法上添加before
和after
回调。钩子可以是:
可以在同一方法上注册多个挂钩。挂钩的方法应该在钩子之前。
E.g:
class Model < ActiveRecord::Base
def method1
end
def method2
end
def method3
end
def method4
end
def update_cache
end
# instance method name as `after` callback parameter
method_hook :method1, :method2, :after => :update_cache
# lambda as `before` callback parameter
method_hook :method1, :method2,
:before => lambda{|name, record| p name;p record}
# lambda as `after` callback parameter
method_hook :method3, :method4,
:after => lambda{|name, record|
Model2.increment_counter(:post_count, record.model2_id)}
end
答案 1 :(得分:1)
这样的事情怎么样?
def notify; puts "Was notified."; end
def method1; end
def method2; end
def method3; end
def original
notify
method1
notify
method2
method3
end
def dry
[:method1, :method2].each do |m|
notify
send(m)
end
method3
end
original
dry