Prev | Current Page 63 | Next

Brad Ediger

"Advanced Rails"

enum_for(:each_value).map{|value| ... }
Examples | 41
That way, we have a small Enumerator object whose each method behaves just as
hash??™s each_value method does. This is preferable to creating a potentially large array
and releasing it moments later. In Ruby 1.9, this is the default behavior if the iterator
is not given a block. This simplifies our code:
hash.each_value.map{|value| ... }
Examples
Runtime Feature Changes
This example ties together several of the techniques we have seen in this chapter. We
return to the Person example, where we want to time several expensive methods:
class Person
def refresh
# ...
end
def dup
# ...
end
end
In order to deploy this to a production environment, we may not want to leave our
timing code in place all of the time because of overhead. However, we probably want
to have the option to enable it when debugging. We will develop code that allows us
to add and remove features (in this case, timing code) at runtime without touching
the original source.
First, we set up methods wrapping each of our expensive methods with timing commands.
As usual, we do this by monkeypatching the timing methods into Person
from another file to separate the timing code from the actual model logic:*
class Person
TIMED_METHODS = [:refresh, :dup]
TIMED_METHODS.each do |method|
# set up _without_timing alias of original method
alias_method :"#{method}_without_timing", method
# set up _with_timing method that wraps the original in timing code
define_method :"#{method}_with_timing" do
start_time = Time.


Pages:
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75