Add URL Mapping on demand
Asked Answered
R

1

0

My grails project has at least 20 controllers each with at least 4 methods each, and it is continuing to grow. I decided to annotate every method like this:

import enums.URLMapped

class HomeController {
    @URLMapped(url="/", alias="home")
    def landingPage() {
        render(view: "/index")
    }
}

How can I append this URL value inside the URLMapping.groovy dynamically? I could do something like:

import enums.URLMapped
import java.lang.reflect.Method
import org.apache.commons.lang.StringUtils
import org.codehaus.groovy.grails.commons.DefaultGrailsControllerClass
import org.codehaus.groovy.grails.commons.GrailsApplication

class UrlMappings {
    static mappings = {
        "/$controller/$action?/$id?(.$format)?"{
            constraints {
                // apply constraints here
            }
        }

        // My annotation crawler/parser
        for(DefaultGrailsControllerClass controller in GrailsApplication.getControllerClasses()) {
            for(Method method in controller.getClazz().getDeclaredMethods()) {
                if(!method.isSynthetic()) {
                    if(method.isAnnotationPresent(URLMapped.class)) {
                        URLMapped url  = method.getAnnotation(URLMapped.class)
                        name "${url.alias()}": "${url.url()}" {
                            action="${method.getName()}"
                            controller="${StringUtils.capitalize(controller.getClazz().getSimpleName().split(/Controller/).getAt(0)}"
                        }
                        /* What I want to achieve above is this static URL:
                            name home: "/" {
                                action="landingPage"
                                controller="Home"
                            }
                         */
                    }
                }
            }
        }
    }
}

But the problem is that static mapping is a closure and you shouldn't suppose to loop (?) inside it. So how can I add my URL? I could always put all static URL for all of our links here, it's just getting tedious to maintain.

Round answered 27/2, 2017 at 8:7 Comment(0)
O
0

I would strongly recommend you get rid of this idea with annotations but to divide your project into several plugins (each - a separate grails-app) tied together with gradle.

Some useful info:

  1. https://docs.gradle.org/current/userguide/custom_plugins.html
  2. https://docs.gradle.org/current/userguide/multi_project_builds.html
Orndorff answered 27/2, 2017 at 17:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.