Where should I use the reuse method in the grail?

I am new to Grails. I would like to create a reusable function that can calculate the percentage (0 - 100%) based on any two input values ​​that I specify. I would like it to be reused in domains and controllers, but it's hard for me to determine where to put this function.

Here is my code:

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
  }

}

Does anyone have any tips on best practices for implementing this? Thank!

+5
source share
1 answer

If you are writing a class (e.g. called TimeUtils.groovy) and put it insrc/groovy/utils

Then add something that does this as a static method:

package utils

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

Then you can call:

def perc = utils.TimeUtils.calcPercentComplete( 8, 24 )

From anywhere in your code

+6
source

All Articles