Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where should I put a reusable method in grails?

Tags:

grails

groovy

I am new to Grails. I would like to create a reusable function that can calculate a percentage (0 - 100%) based on any 2 input values I specify. I would like this to be reusable across domains and controllers, but I am having a hard time figuring out 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 advice on best practices for implementing this? Thanks!

like image 367
Abbazaba Avatar asked Sep 20 '12 12:09

Abbazaba


1 Answers

If you write a class (say called TimeUtils.groovy) and put it in src/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
  }
}

You should then be able to call:

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

From anywhere in your code

like image 118
tim_yates Avatar answered Sep 20 '22 21:09

tim_yates