[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Re: Best practices for Ruby Meta-programming

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


1 Answer

Robert Dober

3/11/2008 11:41:00 PM

0

On Tue, Mar 11, 2008 at 10:40 PM, John Carter <john.carter@tait.co.nz> wrote:
> 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?
Semantically yes, for the implementation
I have no idea, it is probably written in C. The point is what it is good for.
R.
>
>
> 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
>
>
>



--
http://ruby-smalltalk.blo...

---
Whereof one cannot speak, thereof one must be silent.
Ludwig Wittgenstein