Skip to content

Instantly share code, notes, and snippets.

@sstarr
Last active December 26, 2015 06:19
Show Gist options
  • Save sstarr/7107427 to your computer and use it in GitHub Desktop.
Save sstarr/7107427 to your computer and use it in GitHub Desktop.
# - A `Thing` can be 1% - 100% green
# - This is represented on the front end with a doughnut chart
# - The doughnut chart can't be generated since it's in an email
# - To get around this, we have 25 static doughnut images in increments of 4%
# This code takes the percentage and returns the relevant image.
# I'm sure there must be a more sensible way of doing this than using the
# world's longest switch statement. Any ideas?
class Thing
key :percent_green, Integer
def static_doughnut
case percent_green
when 1,2,3,4
"1-4.gif"
when 5,6,7,8
"5-8.gif"
when 9,10,11,12
"9-12.gif"
when 13,14,15,16
"13-16.gif"
when 17,18,19,20
"17-20.gif"
when 21,22,23,24
"21-24.gif"
when 25,26,27,28
"25-28.gif"
when 29,30,31,32
"29-32.gif"
when 33,34,35,36
"33-36.gif"
when 37,38,39,40
"37-40.gif"
when 41,42,43,44
"41-44.gif"
when 45,46,47,48
"45-48.gif"
when 49,50,51,52
"49-52.gif"
when 53,54,55,56
"53-56.gif"
when 57,58,59,60
"57-60.gif"
when 62,62,63,64
"61-64.gif"
when 65,66,67,68
"65-68.gif"
when 69,70,71,72
"69-72.gif"
when 73,74,75,76
"73-76.gif"
when 77,78,79,80
"77-80.gif"
when 81,82,83,84
"81-84.gif"
when 85,86,87,88
"85-88.gif"
when 89,90,91,92
"89-92.gif"
when 93,94,95,96
"93-96.gif"
when 97,98,99,100
"97-100.gif"
end
end
end
@nigel-lowry
Copy link

The ranges follow an arithmetic progression so you just need to get everything together to plug into the arithmetic series formula.

def static_doughnut
  min = 1
  max = 100
  return if percent_green < min or percent_green > max # maintain original interface by doing nothing if outside range

  d = 4 # must be a factor of 'max' if 'min' is 1 for evenly spaced ranges
  n = (percent_green - 1) / d + 1 
  lower_bound = min + (n - 1) * d # arithmetic series formula
  upper_bound = lower_bound + d - 1

  "#{lower_bound}-#{upper_bound}.gif"
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment