GDSL Awesomeness – Delegating Closure Calls

24 / Sep / 2012 by Kushal Likhi 2 comments

hi,

 

Very often we use delegates in our closure calls. It would be great if we could get code-hinting in the closure via the delegates.

 

Now let us take a very simple scenario, where we made a method “with” which delegates the delegate objet to closure and runs it.
[java]

class Delegator {
static def runWith(obj, Closure cl) {
cl.delegate = obj
cl.call()
}
}

Delegator.runWith(new MyDelegate()) {
myDelegateMethod()
def prop = myDlegateProperty
// And so on we can access delegate’s assets
}
[/java]

 

Now we want out IDE to give us syntax-hint inside the closure for delegate’s methods and properties,
This can be achieved by using the following GDSL script:
[java]
//Get the context for all closures
def ctx = context(scope: closureScope())

contributor(ctx, {
//See if closure is called within method "runWith"
def call = enclosingCall("runWith")
if (call) {
//Get the method object of the closure call
def method = call.bind()
//Get class containing that calling method.
def clazz = method?.containingClass
if ("Delegator".equals(clazz?.qualName)) {
//Delegate the closure to the object passed as the first argument.
delegatesTo(call.arguments[0])
}
}
})
[/java]

 

Hurray! now we have syntax completion for delegate’s assets in our closure.

 

Read Further in the “GDSL AWESOMENESS” Series

  1. GDSL Awesomeness – Introduction to GDSL in IntelliJ Idea
  2. GDSL Awesomeness – Understanding Context And Contributors in Detail
  3. GDSL Awesomeness – Defining dynamic property in a class
  4. GDSL Awesomeness – Defining dynamic method in a class
  5. GDSL Awesomeness – Adding Hinting for missingMethod implementation
  6. GDSL Awesomeness – Setting a global context
  7. GDSL Awesomeness – Delegating Closure Calls
  8. GDSL Awesomeness – Defining methods in a closure passed to method of particular name
  9. GDSL Awesomeness – Defining Properties in a closure passed to method of particular name
  10. GDSL Awesomeness – Contributing to classes which match a path/name pattern
  11. GDSL Awesomeness – contributing methods with current class return types or parameters
  12. GDSL Awesomeness – AutoComplete Script for grails-Mail-Plugin “sendMail” closure
  13. GDSL Awesomeness – Getting Code of a method or Field in GDSL Script
  14. GDSL Awesomeness – Advanced Example showing domain properties implementation

 

 

Hope It Helped.
Kushal Likhi

FOUND THIS USEFUL? SHARE IT

comments (2)

Leave a Reply

Your email address will not be published. Required fields are marked *