我的 Grails 应用程序中有一个相当大的标准闭包,我想在我的应用程序的几个地方重用它的一部分。我不想复制我需要重用的部分,而是想将它定义为一个单独的闭包并在需要的地方引用它,但我在语法上有点挣扎。
这是一个简化/缩减的版本,但基本上我的标准看起来像这样:
def criteriaClosure = {
and {
// filtering criteria that I'd like to reuse in lots of places
or {
names.each { name ->
sqlRestriction(getFilteringSql(name), [someId])
}
}
if (isOrganisationChild(childDefaultGrailsDomainClass)) {
sqlRestriction(getFilteringSql(domain), [someArg])
}
// filtering criteria that's specific to this particular method
sqlRestriction(getSomeOtherSql(), [someOtherArg])
}
}
def criteria = domain.createCriteria()
def paginatedList = criteria.list([offset: offset, max: max], criteriaClosure)
我已经尝试将我想要重用的闭包部分定义为变量,并在我的条件闭包中引用它,但是它定义的限制似乎没有被应用。
def reusableClosure = {
and {
or {
names.each { name ->
sqlRestriction(getFilteringSql(name), [someId])
}
}
if (isOrganisationChild(childDefaultGrailsDomainClass)) {
sqlRestriction(getFilteringSql(domain), [someArg])
}
}
}
def criteriaClosure = {
and {
reusableClosure() //this doesn't seem to work
sqlRestriction(getSomeOtherSql(), [someOtherArg])
}
}
我确信这一定是一件非常简单的事情,所以如果这是一个愚蠢的问题,请道歉。有任何想法吗?
最佳答案
我认为您必须将委托(delegate)传递给 reusableClosure
, IE:
def criteriaClosure = {
and {
reusableClosure.delegate = delegate
reusableClosure()
sqlRestriction(getSomeOtherSql(), [someOtherArg])
}
}
关于grails - 重用 Grails 标准闭包的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20194137/