[lnkForumImage]
TotalShareware - Download Free Software

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


 

Forums >

comp.lang.ruby

Re: can there be a "with" construction?

Gennady Bystritsky

10/27/2006 5:59:00 PM

matt neuburg wrote:
> Some languages have a "with" construction, where undefined methods are
> routed to a designated object. Here's an example from UserTalk:
>
> with system.startup {
> string(license)
> }
>
> UserTalk knows what "string" is, but when it can't find "license" it
> reinterprets it as system.startup.license, which works. In
> UserTalk, you
> can even chain these tests:
>
> with system.temp, system.startup {
> string(license)
> }
>
> That means we try system.temp.license and if that doesn't exist we
> proceed to system.startup.license.
>
> So my question is: is Ruby amenable to this kind of construction? Is
> there a way to bend the language to that it acts like this? Thx - m.

Something like this?

def with(*objects)
begin
yield
rescue NoMethodError => exception
o = objects.detect { |_o|
_o.respond_to? exception.name
} or raise

o.send exception.name, *exception.args
end
end

m = with(Time) do
"aaa".now
end

p m
Fri Oct 27 10:57:44 PDT 2006


1 Answer

Jacob Fugal

10/27/2006 6:07:00 PM

0

On 10/27/06, Gennady Bystritsky <Gennady.Bystritsky@quest.com> wrote:
> matt neuburg wrote:
> > Some languages have a "with" construction, where undefined methods are
> > routed to a designated object. Here's an example from UserTalk:
> >
> > with system.startup {
> > string(license)
> > }
> >
> > UserTalk knows what "string" is, but when it can't find "license" it
> > reinterprets it as system.startup.license, which works. In
> > UserTalk, you
> > can even chain these tests:
> >
> > with system.temp, system.startup {
> > string(license)
> > }
> >
> > That means we try system.temp.license and if that doesn't exist we
> > proceed to system.startup.license.
> >
> > So my question is: is Ruby amenable to this kind of construction? Is
> > there a way to bend the language to that it acts like this? Thx - m.
>
> Something like this?
>
> def with(*objects)
> begin
> yield
> rescue NoMethodError => exception
> o = objects.detect { |_o|
> _o.respond_to? exception.name
> } or raise
>
> o.send exception.name, *exception.args
> end
> end

It's a start, but:

1) I don't think we really want to redispatch NoMethodErrors for
messages that had an explicit receiver. Only the ones with implicit
receivers.

2) it stops execution of the block after redispatching the first exception:

with(Time) do
"aaa".now
puts "Never get here"
end # nothing printed

Jacob Fugal