Prev | Current Page 105 | Next

Brad Ediger

"Advanced Rails"

now
(class << object; self end).class_eval do
method_name = "_ _bind_#{time.to_i}_#{time.usec}"
define_method(method_name, &block)
method = instance_method(method_name)
remove_method(method_name)
method
end.bind(object)
end
end
The class_eval block is evaluated in the context of the object??™s singleton class, so the
method created is specific to that object. A method with a (hopefully) unique name is
created, using the Proc as the method body. The instance_method method grabs the newly
created method object as an UnboundMethod from the class. Because we hold a reference to
the method, we can safely remove it from the singleton class using remove_method, and the
method will remain in existence (anonymously). The last line in the class_eval returns
the method from the class_eval; the method is then bound to the given object and returned.
This definition of instance_exec is a Ruby 1.8 workaround. In Ruby 1.9, instance_exec is a
native method. Also note that this implementation is not threadsafe. It tries to be as safe as
possible, qualifying the method names down to the microsecond and putting them in the
respective objects??™ singleton classes, but it will still fail if called twice on the same object
during the same microsecond.
Range
72 | Chapter 2: ActiveSupport and RailTies
Miscellaneous methods core_ext/object/misc.rb
??? Object#returning lets you perform some operations on an object and then return it.


Pages:
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117