GDSL Awesomeness – Delegating Closure Calls
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.
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 }
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:
//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]) } } })
Hurray! now we have syntax completion for delegate’s assets in our closure.
Read Further in the “GDSL AWESOMENESS” Series
- GDSL Awesomeness – Introduction to GDSL in IntelliJ Idea
- GDSL Awesomeness – Understanding Context And Contributors in Detail
- GDSL Awesomeness – Defining dynamic property in a class
- GDSL Awesomeness – Defining dynamic method in a class
- GDSL Awesomeness – Adding Hinting for missingMethod implementation
- GDSL Awesomeness – Setting a global context
- GDSL Awesomeness – Delegating Closure Calls
- GDSL Awesomeness – Defining methods in a closure passed to method of particular name
- GDSL Awesomeness – Defining Properties in a closure passed to method of particular name
- GDSL Awesomeness – Contributing to classes which match a path/name pattern
- GDSL Awesomeness – contributing methods with current class return types or parameters
- GDSL Awesomeness – AutoComplete Script for grails-Mail-Plugin “sendMail” closure
- GDSL Awesomeness – Getting Code of a method or Field in GDSL Script
- GDSL Awesomeness – Advanced Example showing domain properties implementation
Hope It Helped.
Kushal Likhi
Thanks for sharing, this is a fantastic blog. Much obliged.
Some genuinely interesting details you have written.Helped me a lot, just what I was looking for : D.