从插件中修改项目配置的最佳方法是什么?

rdm*_*ler 5 grails plugins

在我尝试编写Grails插件时,我偶然发现了两个问题:

  • 我怎么样修改配置文件中的一个Config.groovyDataSource.groovy从witin的_install.groovy 脚本?向这些文件添加内容很容易,但如何以干净的方式修改它?text.replaceAll()?或者我应该创建一个新的配置文件?
  • 如何获取插件将安装到的当前应用程序的名称?我试图用app.nameappName,但都不起作用.

是否有可能在某处创建一个我尚未找到的插件的好教程?

Big*_* Ed 5

以下是编辑配置文件的示例scripts/_Install.groovy.
我的插件将三个文件复制到目标目录.

  • .hgignore 用于版本控制,
  • DataSource.groovy 替换默认版本,和
  • SecurityConfig.groovy 包含额外的设置.

我更喜欢尽可能少地编辑应用程序的文件,特别是因为我希望在未来几年内更改安全设置.我还需要使用jcc-server-config.properties为我们系统中的每个应用程序服务器定制的文件中的属性.

复制文件很简单.

println ('* copying .hgignore ')
ant.copy(file: "${pluginBasedir}/src/samples/.hgignore",
         todir: "${basedir}")
println ('* copying SecurityConfig.groovy')
ant.copy(file: "${pluginBasedir}/src/samples/SecurityConfig.groovy",
         todir: "${basedir}/grails-app/conf")
println ('* copying DataSource.groovy')
ant.copy(file: "${pluginBasedir}/src/samples/DataSource.groovy",
         todir: "${basedir}/grails-app/conf")
Run Code Online (Sandbox Code Playgroud)

困难的部分是让Grails获取新的配置文件.为此,我必须编辑应用程序grails-app/conf/Config.groovy.我将在类路径中添加两个配置文件.

println ('* Adding configuration files to grails.config.locations');
// Add configuration files to grails.config.locations.
def newConfigFiles = ["classpath:jcc-server-config.properties", 
                      "classpath:SecurityConfig.groovy"]
// Get the application's Config.groovy file
def cfg = new File("${basedir}/grails-app/conf/Config.groovy");
def cfgText = cfg.text
def appendedText = new StringWriter()
appendedText.println ""
appendedText.println ("// Added by edu-sunyjcc-addons plugin");
// Slurp the configuration so we can look at grails.config.locations.
def config = new ConfigSlurper().parse(cfg.toURL());
// If it isn't defined, create it as a list.
if (config.grails.config.locations.getClass() == groovy.util.ConfigObject) {
    appendedText.println('grails.config.locations = []');
} else {
    // Don't add configuration files that are already on the list.
    newConfigFiles = newConfigFiles.grep {
      !config.grails.config.locations.contains(it)
    };
}
// Add each surviving location to the list.
newConfigFiles.each {
    // The name will have quotes around it...
    appendedText.println "grails.config.locations << \"$it\"";
}
// Write the new configuration code to the end of Config.groovy.
cfg.append(appendedText.toString());
Run Code Online (Sandbox Code Playgroud)

唯一的问题是添加SecurityConfig.groovy到类路径.我发现你可以通过在插件中创建以下事件来做到这一点/scripts/Events.groovy.

eventCompileEnd = {
    ant.copy(todir:classesDirPath) {
      fileset(file:"${basedir}/grails-app/conf/SecurityConfig.groovy")
    }
}
Run Code Online (Sandbox Code Playgroud)

埃德.