[英]Augmenting existing methods for all Ruby objects
Often, I see stuff like this: 我经常看到这样的东西:
class Someclass
do_something_to :foo, :bar, :class_level
def foo
puts "Hi!"
end
def bar
end
def self.class_level
puts "Something else!"
end
end
I want to patch Class
or Object
to have my own version of do_something_to
. 我想修补Class
或Object
以拥有自己的do_something_to
版本。 Doesn't need to do anything fancy, a simple printout of the current time vs time at the beginning and end will do. 不需要做任何花哨的事情,只需将当前时间与开始时间和结束时间进行简单打印即可。
Here's a solution that works, except that it doesn't address class-level methods: 这是一个可行的解决方案,除了它不解决类级方法之外:
require 'aspector'
class Class
def do_something_to(*names)
aspector do
around(names) do |proxy, *args, &block|
start_time = Time.now.to_f
proxy.call *args, &block
final_time = Time.now.to_f - start_time
puts final_time
return final_time
end
end
end
end
class MyClass
do_something_to :hey, :derp
def hey
puts "Hey!"
sleep 1
end
def derp x
puts x
sleep 2
end
end
I think something like this should work. 我认为这样的事情应该起作用。
The do_something_method will save the original method and then redefine the modified one by printing timestamps before and after calling the original method. do_something_method将保存原始方法,然后通过在调用原始方法之前和之后打印时间戳来重新定义已修改的方法。
Just one caveat. 请注意。 Make sure you call the do_something_to after the method definition, otherwise it'll not find the original method and will fail. 确保在方法定义之后调用do_something_to,否则它将找不到原始方法并且将失败。
class Class
def do_something_to(method)
class_eval <<-EOS, __FILE__, __LINE__ + 1
alias_method :modified_#{method}, :#{method}
def #{method}
puts Time.now.to_i
modified_#{method}
puts Time.now.to_i
end
EOS
end
end
class MyClass
def test_method
puts "Hello world"
end
do_something_to :test_method
end
MyClass.new.test_method
# => 1403105585
# => "Hello world!"
# => 1403105586
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.