Some "core" frameworks use monkey patches / open classes

I am curious to use a feature known as open classes or monkey patching in languages ​​like Ruby, Python, Groovy, etc. This feature allows you to make changes (for example, add or replace methods) to existing classes or objects at runtime.

Does anyone know if core frameworks (like Rails / Grails / Zope) use this capability to provide services to a developer? If yes, please provide examples.

+1


a source to share


3 answers


Rails does this to a (IMHO) ridiculous degree.



+8


a source


.Net resolves it using extension methods.



Linq in particular relies heavily on extension methods decapitated on the IEnumerable interface.

+2


a source


An example of its use in the Java platform (since you mentioned Groovy) is temporary weaving with something like the AspectJ and JVM tools. In this particular case, however, you have the option of using time compilation. Interestingly, one of my recent SO questions was about problems using this load time, with some recommending compile time as the only reliable option.

An example of AspectJ that uses load (runtime) time to provide a useful service to a developer would be the Spring @Configuration annotation, which allows Dependency Injection on an object not created with Spring BeanFactory.

You specifically mentioned modifying the method (or how it works), and an example of what's used is an aspect that intercepts the HTTP request before sending it to the handler (some kind of controller method or doPost, etc.) and check to see if the user is allowed access to this resource. Then your aspect may decide to return - prematurely - a redirect to login response. Without changing the content of the method as such, you are still changing the way the method works, changing the return value it otherwise produced.

+1


a source







All Articles