[lnkForumImage]
TotalShareware - Download Free Software

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


 

Forums >

comp.lang.ruby

library method isolation

William Morgan

1/8/2005 12:38:00 AM

Dear gurus,

I often add utility methods to Hash, Enumerable, etc. For applications
this is fine, but for a library, I feel like I should avoid leaving such
"method detritus" around in users' namespaces.

Is there a way to extend/modify existing classes or modules only within
the context of a particular ("library") module?

My first idea had some problems:

module Library

class Hash < ::Hash
def extramethod
# ...
end
end

Hash.new.extramethod # fine
{}.extramethod # problem, but I can work around
[1,2,3].map { |x| x + 1 }.extramethod # big problem

end

How do others deal with this?

Thanks for any insight,

--
William <wmorgan-ruby-talk@masanjin.net>


2 Answers

Charles Mills

1/8/2005 3:38:00 AM

0

William Morgan wrote:
> Dear gurus,
>
> I often add utility methods to Hash, Enumerable, etc. For
applications
> this is fine, but for a library, I feel like I should avoid leaving
such
> "method detritus" around in users' namespaces.
>
I think your looking for selector namespaces. This is planned for Ruby
2.0.
http://rubygarden.org...
Google will turn up more info.

(...)
> Is there a way to extend/modify existing classes or modules only
within
> the context of a particular ("library") module?
>
(...)
> How do others deal with this?

Not sure how people are currently dealing with this issue, other than
ignoring it...

-Charlie

William Morgan

1/8/2005 4:16:00 PM

0

Excerpts from Charles Mills's mail of 7 Jan 2005 (EST):
> > I often add utility methods to Hash, Enumerable, etc. For
> > applications this is fine, but for a library, I feel like I should
> > avoid leaving such "method detritus" around in users' namespaces.
>
> I think your looking for selector namespaces. This is planned for
> Ruby 2.0. http://rubygarden.org...

Thanks. That would certainly solve this issue. The wiki page mentions
something about Ruby libraries that implement selector namespaces; I
wonder if the author of that statement had something specific in mind or
whether it was just a rhetorical device....

In the mean time, I've been moving all utility methods into modules and
making liberal use of 'extend' like so:

hash = @array.map { |x| trans(x) }.extend(HashUtil).utilfunc

which is irritating, and unnecessarily slow, and doesn't work in all
cases, but is sufficient for the purposes of namespace purity. :)

Thanks for your help,

--
William <wmorgan-ruby-talk@masanjin.net>