Is there a way to turn off the Codenarc NoDef rule for Grails controller actions? The rule is a good practice to follow in general but since some actions return a value and some don't, we typically use def to support all variants. I looked around a bit to see if this rule can be turned off for controller actions but came up empty. Does anyone know?
-
2"we typically use def to support all variants" - Be aware the if the method return type is `void`, per https://github.com/grails/grails-core/blob/bd7741b646e13da598926cf118fad0221590e567/grails-plugin-controllers/src/main/groovy/org/grails/compiler/web/ControllerActionTransformer.java#L303 it will not be configured as a controller action. I know that isn't what you are asking about, but want to point that out in case that might prove helpful. – Jeff Scott Brown Oct 22 '15 at 20:06
3 Answers
You can't exclude specifically Controller actions and you can't exclude by class name either (using the doNotApplyToClassNames
property) because the rule is applied by file level and not class.
The closest I could get was to exclude the whole Controller from the rule like this:
NoDef.doNotApplyToFilesMatching = /.*Controller.groovy/
I also recommend excluding Services
and grailsApplication
injection from the rule, as it doesn't bother me to have defs there. For example:
class SomeService {
def otherService
def grailsApplication
}
The rule configuration for this should be:
NoDef.excludeRegex = /(.+Service|.+Controller|grailsApplication)/

- 1,465
- 1
- 15
- 17
I read the blog post and tried the doNotApplyToClassNames option, but it didn't work.
From the documentation:
NoDef Rule
Since CodeNarc 0.22
NOTE: This rule applies to the text contents of a file rather than a specific class, so it does not support the applyToClassNames and doNotApplyToClassNames configuration properties.
So you cant actually use the doNotApplyToClassNames parameter, but there is a excludeRegex
property that you can use, but you would need to come up with a regular expression to exclude your controller actions.
Regular expression describing names of attributes, parameters or methods that could be precede by the def keyword.

- 5,295
- 5
- 49
- 79
If you are using codenarc plugin then I believe you should be able to disable some of the rules in codenarc rule set file as mentioned in this blog
http://www.tothenew.com/blog/grails-clean-code-configure-codenarc-plugin/

- 619
- 3
- 7
-
You cannot configure this specific Codenarc rule by filename. Check @j4y answer. – mathifonseca Dec 28 '16 at 14:30