John Carter
3/11/2008 9:41:00 PM
On Tue, 11 Mar 2008, Robert Dober wrote:
> def attr_reader *atts
> atts.each do |att|
> define_method att do instance_variable_get "@#{att}" end
> end
> end
>
> is definitely for the programmer, it also should rather run at runtime
> than at compile time.
This topic is about Best Practices for Meta-Programming.
And you have just handed me a brilliant example of why human readable
intermediate representation _is_ Best Practice...
Hmm. Is
attr_read :foo
really equivalent to a plain getter?
define foo
@foo
end
The way I read your code it's equivalent to...
define foo
instance_variable_get "@foo"
end
Which is probably slower.
Either way the very fact we need to think about it illustrates the
value of human readable intermediate representations!
How about...
def make_getter( att)
"define #{att}
@#{att}
end
"
end
def Module.attr_read( *atts)
atts.each do |att|
self.class_eval( make_getter( att))
end
end
Note I have a bug in make_getter...
The class_eval failed for some mysterious reason, so I said...
puts make_getter("foo")
And got...
define foo
@foo
end
Oops! I see the problem...it should be...
def make_getter( att)
"def #{att}
@#{att}
end
"
end
And I get...
puts make_getter("foo")
And got...
def foo
@foo
end
Yip that worked.
John Carter Phone : (64)(3) 358 6639
Tait Electronics Fax : (64)(3) 359 4632
PO Box 1645 Christchurch Email : john.carter@tait.co.nz
New Zealand