On 10/8/07, Jay Levitt <jay+news / jay.fm> wrote:
> Let me start off by saying that I'm SURE this is either a bad idea,
> impossible to implement, or both.  I just can't enumerate the reasons why,
> and I thought this would be a good group to shoot it down.
>
> Since it's so easy to add new functionality to Ruby core classes (which are
> open for extension), many libraries do.  Rails adds all sorts of things in
> Active Support, and other frameworks and libs do similar things.  Gems does
> with Time::today, but is about not to, so that it doesn't step on anyone
> else's Time machines.
>
> Yet adding, say, String#to_leetspeak is a much cleaner alternative than
> defining a global to_leetspeak(String) method.  The key is to stop the
> leetspeak from leaking into other modules.
>
> What if class definitions were viewed through a magic prism, where only
> those classes looking from the right perspective saw the new extensions?
> Mind you, I have no idea how to partition the codespace in any sane manner
> - even from a design spec point-of-view.  Should ActiveRecord see Og's
> extensions?  Probably not; but ActionView and ActionPack might want to
> share.  And what happens if Og passes a Hash to ActiveRecord that happens
> to include an Og-provided Time#today in it?
>
> I dunno.  On the surface it seems that there must be some nicer way to add
> better locality of reference to core extensions, but I can't imagine how it
> would be implemented, how it should work, or if it would even be a good
> idea.  Just some good old Sunday night musings.
>
> Do other languages do anything like that?
>
> --
> Jay Levitt                |
> Boston, MA                | My character doesn't like it when they
> Faster: jay at jay dot fm | cry or shout or hit.
> http://www.jay.fm         | - Kristoffer
>
>

I don't want to get too caught up in your example, but I think that's
one spot where a new class is better than defining a new method on
String.  For example, what happens if you do "my cool
sentence".to_leetspeak.to_leetspeak?  Does it just become some super
garbled stuff?

The classic example from Java-land is escaped and unescaped strings in
a webapp.  When you get some input from the user, you create an
escaped string at the top layer.  new EscapedString(userInput).  Then
you pass that around, and in each layer you can call new
EscapedString(the_string), which escapes it if it's a basic string and
just returns itself if it's already escaped.  That way you assume that
each string is unsafe, but you don't get bit by funky implementation
details.

Anyway, I think it would be cool if things were sandboxed.  You could
register them globally in your app

String.use_extensions :leetspeak

so now every string in the app has #leetspeak on it.  Or you could
sandbox them in a block

String.use_extensions :leetspeak do
  "I am cool".to_leetspeak  # => "I 4m k3w1"
end

"I am not".to_leetspeak  # => NoMethodError

Pat