Safer monkey-patching?

Sometimes (or often, depending on your use) it is useful to add or
override
methods to an already existing class, aka monkey-patching. Would it be
useful
to subclass an existing object, while still using the same class-name -
in
essence, creating an extended local version of the class:

String = Class.new(String) do
def size()
return -1
end
end

string = String.new << “foo”
puts string.size

I realize this is re-assigning a constant, but it’s more for
demonstration
purposes. Now anything within lexical scope will use the new class,
while
other methods will use the original.

Mike

On Apr 14, 11:45 pm, Mike A. [email protected] wrote:

Sometimes (or often, depending on your use) it is useful to add or override
methods to an already existing class, aka monkey-patching. Would it be useful
to subclass an existing object, while still using the same class-name - in
essence, creating an extended local version of the class:

I’d like to differentiate monkey-patching from clean extensions. While
it may not be commonly thought of this way, to me monkey patching is
overriding an existing method, not simply adding a new method. Hence
monkey patching is a dangerous activity and deserves a negative
hallmark. Where as simply adding a new method is generally safe, the
main issue being merely potential name clashes with others doing the
same.

purposes. Now anything within lexical scope will use the new class, while
other methods will use the original.

First problem, it doesn’t work unless you use String.new to create all
your new strings. Next problem is how to handle passing off your new
string to external lib? Will you reconvert it to regular String to be
on the safe side? (And of course there’s no safe guarding String’s own
internal methods :wink:

The idea has been discussed before, long time ago. I once suggested it
as a means of selector namespaces. I believe Austin Z.'s comment
was something about “chaos”. But I’m still not sure why he thought
this. There is perhaps some merit to the idea. But it would certainly
need to be explored throughly.

In any case, if you are doing something that you feel warrants this
level of safe guarding, then just be explicit about it. Create a new
String class: ‘class MyString < String’.