Use the groovy category in the groovy shell

I work under some DSLs using the Groovy categories, and I would like to find a way to use my DSL with the Groovy shell without an explicit entry use(MyCategory){ myObject.doSomething() }for each command.

For example, suppose I have the following category of toys:

class MyCategory {
    static Integer plus(Integer integer, String string){
        return integer + Integer.valueOf(string)
    }
}

Then I can use this category in the groovyshfollowing way:

groovy> use(MyCategory){ 2 + '3' } //gives 5

So, is there a way to configure MyCategoryglobally for all teams groovysh, so there is no need to wrap my commands every time in use(MyCategory) { ... }? For instance:

groovy> useGlobally(MyCategory); //call something like this only once
groovy> 2 + '3' //automatically uses MyCategory and gives 5
+4
source share
1 answer

, . metaClass ?

groovy:000> class MyCategory {
groovy:001>     static Integer plus(Integer integer, String string){
groovy:002>         return integer + Integer.valueOf(string)
groovy:003>     }
groovy:004> }
===> true
groovy:000> Integer.metaClass.mixin MyCategory
===> null
groovy:MyCategory@131fa4b> 2 + '4'
===> 6
groovy:MyCategory@131fa4b> 

. .

class MyCategory {
    static global() {
        MyCategory.metaClass.methods
            .findAll { it.isStatic() && !it.name.startsWith("__") && it.name != "global" }
            .each { it.nativeParameterTypes[0].mixin MyCategory }
    }

    static Integer plus(Integer integer, String string){
        return integer + Integer.valueOf(string)
    }

    static String yell(String a, times) {
      a.toUpperCase() * times + "!!!"
    }
}


MyCategory.global()


assert "a".yell(3) == "AAA!!!"
assert 2+'3' == 5
+2

Source: https://habr.com/ru/post/1542211/


All Articles