I once came across a Ruby library (I’m not sure it was ever packaged as a gem) that allowed you to conveniently apply temporary modifications to Ruby modules. These modifications would only be active within blocks executed within a ‘with’ declaration, like:
with(modifications) do
[interesting stuff requiring the modifications]
end
It made sure you didn’t need to permanently pollute (core) modules just to get something special done in certain places.
As a specific example of what I want to do: I would like to define an ‘in?’ method on Fixnum, so users of an internal DSL can type:
if value.in? [12, 16, 27, 28]
[do something interesting]
end
I would wrap the DSL evaluation with a ‘with’ method and I wouldn’t have to pollute Fixnum with this in? method. I know this isn’t too hard to do, but there are probably some dark corners and I had the impression this library was very convenient for this purpose.
Does anyone know the name of this library I am looking for? I seem to recall it was something like ‘plusplus’, but Google doesn’t give me anything.
I finally came across the answer: the Rewrite gem by raganwald. Unfortunately, it was only a proof of concept and not much has come of it. It works by parsing the Ruby into an AST, mangling the tree and converting the result back to Ruby. This is of course incredibly powerful, but raganwald never got around to introducing general tools to implement specific manglings, and creating a new one is, in his own words, ‘torturous’.
Implementing the
in?method on String would mean searching the AST for the specific S-expression that represents callingin?on a String and converting that to a different method call; probably anin?(string, args)in the local namespace. This soon turns into the problem of static type checking, lest you interpret everyin?as aString#in?.