从用户定义的脚本创建 "unless" 语句作为绑定

Create "unless" statement as a binding from user defined script

我有一个任务,我需要为用户脚本实现一个处理器,其中脚本的一部分 unless 出现并且它的行为需要与 if statement 相反。有没有一种方法可以创建一个 binding 将表现得像那样。 我是 Groovy 的新手,所以我的解释可能不是很清楚,但我的代码可以更多地说明我的问题。用 if statement 替换 unless 效果很好,但我需要一个制作 unless.

的想法
static List<String> filterSitesByUserScript(String userScript, List<String> sites) {

  //properties
  List<String> rememberedSites = new ArrayList<String>()

  //binding
  def binding = new Binding()
  binding['allSites'] = sites
  binding['rememberedSites'] = rememberedSites
  binding['download'] = {String site ->
      new URL(site).getText()
  }
  //binding['unless'] = {statement -> statement == !statement}
  binding['siteTalksAboutGroovy'] = { content -> content.contains("groovy") || content.contains("Groovy") }
  binding['remember'] = { String site -> rememberedSites.add(site)}

  //groovy shell
  GroovyShell shell = new GroovyShell(binding)
  shell.evaluate(userScript)

  return rememberedSites
}

//A test user script input.
String userInput = '''
   for(site in allSites) {
       def content = download site
       unless (siteTalksAboutGroovy(content)) {
           remember site
       }
   }
   return rememberedSites
'''

//Calling the filtering method on a list of sites.
sites = ["http://groovy.cz", "http://gpars.org", "http://groovy-lang.org/", "http://infoq.com", "http://oracle.com", "http://ibm.com"]
def result = filterSitesByUserScript(userInput, sites)
result.each {
    println 'No groovy mention at ' + it
}
assert result.size() > 0 && result.size() < sites.size
println 'ok'

如果要执行以下代码:

unless (siteTalksAboutGroovy(content)) {
    remember site
}

您可以创建一个绑定 unless 来存储带有两个参数的闭包:

binding['unless'] = { test, block -> if (!test) block() }

仅当第一个参数 test 为 false 时,此闭包才会执行 block()。对于您的示例 运行,带有 unless 闭包的代码将产生以下输出:

No groovy mention at http://infoq.com
No groovy mention at http://oracle.com
No groovy mention at http://ibm.com