how to include groovy dsl script from one groovy file to another

kalvimani niraimadaipandian :

I have created a custom dsl command chain using methods in a groovy scripts . I have a problem in accessing this command chain from another groovy file . Is there a way to achieve the functionality ?

I have tried using "evaluate" which is able to load the groovy file , but it is not able to execute the command chain. I have tried using Groovy shell class , but was not able to call the methods.

show = { 
        def cube_root= it
}

cube_root = { Math.cbrt(it) }

def please(action) {
    [the: { what ->
        [of: { n ->
            def cube_root=action(what(n))
                println cube_root;
        }]
    }]
}

please show the cube_root of 1000

Here I have a CubeRoot.groovy in which executing "please show the cube_root of 1000" produces the result as 10

I have another groovy file called "Main.groovy" . Is there a way to execute the above command chain directly in Main.groovy as "please show the cube_root of 1000" and get the desired output ?

Main.groovy

please show the cube_root of 1000

daggett :

there is no include operation in groovy/java

and you could use GroovyShell

if you could represent your "dsl" as closures then for example this should work:

//assume you could load the lang definition and expression from files  
def cfg = new ConfigSlurper().parse( '''
    show = { 
            def cube_root= it
    }

    cube_root = { Math.cbrt(it) }

    please = {action->
        [the: { what ->
            [of: { n ->
                def cube_root=action(what(n))
                    println cube_root;
            }]
        }]
    }  
''' )

new GroovyShell(cfg as Binding).evaluate(''' please show the cube_root of 1000 ''')

another way - use class loader

file Lang1.groovy

class Lang1{
    static void init(Script s){
        //let init script passed as parameter with variables 
        s.show = { 
           def cube_root= it
        }
        s.cube_root = { Math.cbrt(it) }

        s.please = {action->
            [the: { what ->
                [of: { n ->
                    def cube_root=action(what(n))
                        println cube_root;
                }]
            }]
        }  
    }
}

file Main.groovy

Lang1.init(this)

please show the cube_root of 1000

and run from command line: groovy Main.groovy

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=158220&siteId=1