Reputation: 513
I want to be able to create global functions, meaning a function I can use across controllers, kind of like helper methods.
So in one controller I could do
useful_function(string)
etc... Is this possible?
I did create a class in src/groovy called SiteHelper
, am I on the right track? I want the methods of the class SiteHelper
to be able to be used throughout controllers.
Upvotes: 0
Views: 1228
Reputation: 122364
The standard way to share logic between different components in Grails is to put it in a service, or alternatively in a taglib in the case of functions that need access to web-layer things like request/response/params/session/flash. You can call taglib tags as methods from any controller action:
MyTagLib.groovy
class MyTagLib {
def sayHello = { attrs, body ->
out << "Hello ${attrs.name}"
}
}
MyController.groovy
def someAction() {
def greeting = sayHello(name:"Ian")
// ...
}
Upvotes: 0
Reputation: 75671
You can add it to the metaclass of all controller classes, for example in BootStrap.groovy
:
class BootStrap {
def grailsApplication
def init = { servletContext ->
for (cc in grailsApplication.controllerClasses) {
cc.clazz.metaClass.useful_function = { String s ->
return ...
}
}
}
}
Upvotes: 3
Reputation: 7576
Yes, you're mostly on the right track. You may want to look at making it as a part of service layer.
http://grails.org/doc/latest/guide/services.html
Upvotes: 4
Reputation: 60768
I don't get what is nontrivial about this. It sounds exactly what Apache's StringUtils
class or IOUtils
class does. Yes, creating a SiteHelper
with static methods and importing it will do what you want and is the typical practice for this in Java-influenced (and many other) languages.
Upvotes: -2