[lnkForumImage]
TotalShareware - Download Free Software

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


 

Forums >

comp.lang.ruby

Conditional class extension

Trans

10/8/2006 9:54:00 PM

Is there a better way to do conditional class extension?

module Foo
if const_get(:Bar)
class Bar
def x; end
end
end recue nil
end

The 'if const_get ... rescue nil' doesn't seem very elegant.

Thanks,
T.

4 Answers

Joel VanderWerf

10/8/2006 10:08:00 PM

0

Trans wrote:
> Is there a better way to do conditional class extension?
>
> module Foo
> if const_get(:Bar)
if defined? Bar

That works if you are referring literally to Bar, but not if you just
have a variable referring to a string that might or might not be defined
as a constant in Foo. In that case, you could use constants.include?(str).

> class Bar
> def x; end
> end
> end recue nil
> end
>
> The 'if const_get ... rescue nil' doesn't seem very elegant.
>
> Thanks,
> T.
>


--
vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407

Florian Frank

10/8/2006 10:09:00 PM

0

Trans wrote:
> Is there a better way to do conditional class extension?
>
> module Foo
> if const_get(:Bar)
> class Bar
> def x; end
> end
> end recue nil
> end
>
> The 'if const_get ... rescue nil' doesn't seem very elegant.
>
if defined? Foo::Bar
# ...
end

--
Florian Frank


Ross Bamford

10/8/2006 10:57:00 PM

0

On Mon, 2006-10-09 at 06:55 +0900, Trans wrote:
> Is there a better way to do conditional class extension?
>
> module Foo
> if const_get(:Bar)
> class Bar
> def x; end
> end
> end recue nil
> end
>
> The 'if const_get ... rescue nil' doesn't seem very elegant.

Just a small change, but why not just ask if const_defined? ?

--
Ross Bamford - rosco@roscopeco.REMOVE.co.uk


Trans

10/9/2006 4:21:00 AM

0


Ross Bamford wrote:
> On Mon, 2006-10-09 at 06:55 +0900, Trans wrote:
> > Is there a better way to do conditional class extension?
> >
> > module Foo
> > if const_get(:Bar)
> > class Bar
> > def x; end
> > end
> > end recue nil
> > end
> >
> > The 'if const_get ... rescue nil' doesn't seem very elegant.
>
> Just a small change, but why not just ask if const_defined? ?

Oh yea! :-)

Thanks,
T.