Hi, There could be cases where we would need to inject some methods or properties in all GSP pages. As we know that the GSP pages extends GroovyPage class, hence injecting properties/methods in GroovyPage class can solve out purpose. Example: Lets add appVersion property and a method to provide logo link irrespective […]
Blog teach you : how to enhance http request object by adding helper methods using groovy meta programming. The blog contains most commonly methods to request object such as isAjax, siteUrl, isMobileBrowser, remoteIPAddress etc. Once they are injected from Bootstrap.groovy init closure, the new methods are available in controllers and filters. Blog shows some use cases where these helper methods has been used successfully.
As we all know that groovy is a dynamic programming language, so we can add any method to any class at runtime. First, let’s see a small and simple example of metaProgamming given below, in which we are adding a method (isEvent) into an Integer class. [groovy] Integer.metaClass.isEven = { -> // only (->) sign […]
Restricting the length of a string on gsps is a common scenario in most of our projects. Groovy’s metaprogramming magic made it too simple for me. I added the following lines of code to Bootstrap.groovy: Object.metaClass.trimLength = {Integer stringLength -> String trimString = delegate?.toString() String concatenateString = “…” List separators = [“.”, ” “] if […]
I recently came across a way in Groovy to define a class which can have dynamic getters and setters and properties can be added on the fly. The following code creates a class “MyExpandableClass” and defines two methods in the “getProperty and setProperty”. If we define these two methods in a groovy class, then calls […]