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

我只是一个虾纸丫 提交于 2019-12-22 17:54:08

问题


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


回答1:


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



来源:https://stackoverflow.com/questions/55540716/how-to-include-groovy-dsl-script-from-one-groovy-file-to-another

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!