我应该在grails中将可重用方法放在哪里?

我应该在grails中将可重用方法放在哪里?,grails,groovy,Grails,Groovy,我不熟悉Grails。我想创建一个可重用的函数,它可以根据我指定的任何2个输入值计算百分比(0-100%)。我希望这是跨域和控制器可重用的,但我有一个困难的时间来弄清楚这个功能放在哪里 这是我的密码: def calcPercentComplete(hoursComp, hoursReq) { def dividedVal = hoursComp/hoursReq def Integer result = dividedVal * 100 // results will have

我不熟悉Grails。我想创建一个可重用的函数,它可以根据我指定的任何2个输入值计算百分比(0-100%)。我希望这是跨域和控制器可重用的,但我有一个困难的时间来弄清楚这个功能放在哪里

这是我的密码:

def calcPercentComplete(hoursComp, hoursReq) {
  def dividedVal = hoursComp/hoursReq
  def Integer result = dividedVal * 100

  // results will have a min and max range of 0 - 100.
  switch(result){
    case{result > 100}:
      result = 100
      break

    case {result <= 0}:
      result =  0
      break

    default: return result
  }

}
def calcPercentComplete(小时补偿,小时需求){
def dividedVal=小时补偿/小时需求
def整数结果=dividedVal*100
//结果的最小和最大范围为0-100。
开关(结果){
案例{result>100}:
结果=100
打破
案例{result如果您编写一个类(比如称为
TimeUtils.groovy
)并将其放入
src/groovy/utils

然后添加一些可以作为静态方法执行此操作的内容:

package utils

class TimeUtils {
  static Integer calcPercentComplete(hoursComp, hoursReq) {
    Integer result = ( hoursComp / hoursReq ) * 100.0
    result < 0 ? 0 : result > 100 ? 100 : result
  }
}

无论您的代码在哪里

感谢您的回复。这看起来非常优雅。我会尝试一下,让您知道它是如何工作的。@Abbazaba很乐意帮助您!祝您玩得开心!
def perc = utils.TimeUtils.calcPercentComplete( 8, 24 )