Michal Zmuda
Michal Zmuda

Reputation: 5621

Reusable Grails controller helper methods

How to create reusable Grails controller helper methods which can be used in many controllers?

Right not I have few private methods in one controller. I want to share them with other controllers.

I would like have access to params, redirect etc.

Upvotes: 5

Views: 1161

Answers (3)

Graeme Rocher
Graeme Rocher

Reputation: 7985

The correct way to share code between controllers is to abstract the logic into a service. See

http://grails.org/doc/latest/guide/services.html

Note that if the service is not required to be transactional you should mark it as such.

If however you have web related logic (such as writing templates or markup to the output stream) then you can also use tag libraries to share logic, as tags can be invoked from controllers. See:

http://grails.org/doc/latest/guide/theWebLayer.html#tagsAsMethodCalls

Upvotes: 4

Iván López
Iván López

Reputation: 944

You can use Mixins to you put all your common code:

// File: src/groovy/com/example/MyMixin.groovy
class MyMixin {
    private render401Error() {
        response.status = 401
        def map = [:]
        map.message = "Authentication failed"

        render map as JSON
    }
}

Now in a controller you can do something like this:

// File: grails-app/controller/com/example/OneController.groovy
@Mixin(MyMixin)
class OneController {
    public someAction() {
        if (!user.isAuthenticated) {
            // Here we're using the method from the mixin
            return render401Error()
        }
    }
}

Just one final advice: Mixins are applied during runtime so there is a little overhead.

Upvotes: 2

Bob Brown
Bob Brown

Reputation: 1098

The simplest answer is to create a class in src with a bunch of static methods and pass everything around as parameters, see: http://grails.org/doc/2.3.8/guide/single.html#conventionOverConfiguration

...or else create a controller base class that all other controllers extend from?

That said, I wonder if you are actually looking for scoped services? See http://ldaley.com/post/436635056/scoped-services-proxies-in-grails.

Upvotes: 1

Related Questions