Thursday, 12 September 2013

how to DRY this code?

how to DRY this code?

I have the following line of code in several of my models:
def average(scores)
# get average of scores and round to two decimal places
average = scores.inject{ |sum, el| sum + el }.to_f / scores.size
average.round(2)
end
I've tried to put it in various helper files, with varying success - but
the problem isn't that I can't getting working, it's that it takes some
ugly code and/or extra files (modules, etc) just to include this method in
all of models - and that's raising some red flags. It shouldn't be that
hard.
Helper code is easy for controllers and views, but seems really
counter-intuitive for models - at the same time, it seems silly to have
(literally) the exact same code in 4 places. What's the best way to dry
this out?
update
I want to use the average helper inside of each model's methods - which
are different in every case, but for the last line where everything is
averaged - like so:
def avg_for(student)
scores = []
self.evals.map do |student_id, evals|
evals.select {student_id == student.id}.each do |eval|
scores << eval.score
end
end
average(scores) #here!
end

No comments:

Post a Comment