Ruby Metaprogramming gone wild
Watching the Dave Thomas’ screencasts I’ve learnt a few more interesting ways to use Ruby’s metaprogramming features:
conditional method definition
class Foo
def a
def b
end
end
endb will be created only when a is called. This might be useful the correct order of method calling.
methods self replacement
class Foo
def calculate
def calculate
@x
end
@x = super_expensive_calculation
end
endThe first time the method is called it performs some expensive operations and then replaces itself to use a cached value.