5 ms·
After reading that article, I'm wondering: what's the value of Ruby refinements over dynamically-scoped monkey-patching? Taking the String.camelize example fro
by aphexairlines 14y ago
After reading that article, I'm wondering: what's the value of Ruby refinements over dynamically-scoped monkey-patching? Taking the String.camelize example from the article, you could write in Perl:
sub withCamelize (&) {
my ($thunk) = @_;
local *{'String::camelize'} = sub { ... };
$thunk->()
}
sub camelize_and_join {
my ($str_ary) = @_;
withCamelize {
join ', ', map { $_->camelize } @$str_ary
}
}
So you can probably already accomplish the same with Ruby's equivalent of 'local' for dynamic scoping.
- tsewlliw 14y agoWow, that reminds me of the classloader magic Eclipse/OSGi does so that plugins that depend on different versions of the same library can work together in the same JVM.
- aardvark179 14y agoThat kind of local class alteration is very different from the kind of tricks done in OSGi. In OSGi a class is the same no matter what context you're in, it's just that the context you're in affects the look up from class name to class. So all the caching or optimisations you might do against classes are still valid. Refinements mean things like method lookup are sensitive to the context and become much more fun.
- draegtun 14y agoAs aardvark179 already mentioned this is different. There are modules on CPAN which will allow you to also do class/module path munging like this and it's fully baked into Perl6: http://perlcabal.org/syn/S11.html#Versioning http://perlcabal.org/syn/S11.html#Versioning
- djur 14y agoRuby doesn't have an equivalent of Perl's 'local'.
- gamache 14y agoFirst, Ruby has no built-in way to accomplish dynamic scoping. Perl is Very Powerful. Second, refinements apply lexically. Consider a class A where refinements have been declared, and a class B where they have not. Class A code calls Class B code. Class B code will not see class A's refinements. In the case of dynamic scope, the refinements in use by class A would be visible to class B code, when called from code within class A.
- draegtun 14y agoYes having dynamic scoping gives Perl a very powerful programming instrument. And the lack of dynamic scoping in Ruby can cause problems elsewhere: http://news.ycombinator.com/item?id=5072925 http://news.ycombinator.com/item?id=5072925 PS. I seem fond of dynamic scoping because I've posted lots of examples here on HN: http://www.hnsearch.com/search#request/all&q=draegtun+dynamic+local&start=0 http://www.hnsearch.com/search#request/all&q=draegtun+dy...