13

I am currently reading through and working the examples in Getting Started with Grails, Second Edition by Scott Davis & Jason Rudolph.

This book was written using Grails 1.2.

They have a code sample where they create a debug() method that is called by beforeInterceptor and explained that since debug() is a method, it is not exposed out to the user via URL. They explain that Closures are exposed as Controller Actions to the End User, but methods are not.

I also saw on the Grails 1.3 documentation, they allude to a regular method:

def auth() { ... } 

being treated as private because it is a method, not a closure. Which was true as of Grails 1.3.

However, as of Grails 2.0.0, Controller Actions can be implemented as both methods and closures.

This led me to wonder (and try to figure out) a way to replicate the functionality that is available in pre-Grails 2.0.0 of creating a method in a Controller that does not get exposed out to the end user.

I thought of 2 possible approaches and was wondering which would be better style / practice and why?

  1. Setting accessor as private, i.e. private def auth()
  2. Setting allowedMethods for the method to empty string:

    static allowedMethods = [save: "POST", update: "POST", delete: "POST", auth: ""]
    

both approaches seemed to accomplish the desired effect. However, the first approach one gives a HTTP Error Code 404, and the second approach gives a HTTP Error Code 405.

Does anyone know which approach would be preferable? Also, are there any other approaches, or a "best practices technique" for doing so?

2 Answers 2

15

In Grails 2.0, any methods marked as private or protected are not considered actions.

Marking a method in this way would be more informative for maintenance reasons, because it is visible right at the method declaration whether the method is actionable instead of having to look back at the allowedMethods variable. Also, an inaccessible method won't accidentally be made accessible if its declaration is removed or not added to allowedMethods.

4

It is best to mark it as private because the 404 hides that there is anything there where the 405 could be used to know that there was a function called that. (Not that it would be of much use.)

Also marking the method private is nice as it shows at the method that it is not an action.

1
  • 2
    +1, methods that should not be exposed just should not be "exposed", not "not allow".
    – shihpeng
    Oct 27, 2013 at 17:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.