Last active
December 20, 2015 18:08
-
-
Save justinhennessy/6173402 to your computer and use it in GitHub Desktop.
Class methods discussion
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def user_with_highest_kilometers | |
highest = User.new | |
users.each do |user| | |
highest = user if user_distance_sum(user) > user_distance_sum(highest) | |
end | |
highest | |
end | |
def user_with_highest_ascent | |
highest = User.new | |
users.each do |user| | |
highest = user if user_ascent_sum(user) > user_ascent_sum(highest) | |
end | |
highest | |
end | |
def user_with_highest_achievements | |
highest = User.new | |
users.each do |user| | |
highest = user if user_achievement_sum(user) > user_achievement_sum(highest) | |
end | |
highest | |
end | |
private | |
def user_distance_sum(user) | |
sum_stat(user, :distance) | |
end | |
def user_ascent_sum(user) | |
sum_stat(user, :ascent) | |
end | |
def user_achievement_sum(user) | |
sum_stat(user, :achievements) | |
end | |
def sum_stat(user, stat_to_sum) | |
user.activities.where("date >= '" + start_date.to_s + "' and date <= '"\ | |
+ end_date.to_s + "'").sum(stat_to_sum) | |
end |
Author
justinhennessy
commented
Aug 9, 2013
class Challenge
def user_with_highest_kilometers
users.highest_kilometers_within_period period
end
def period
OpenStruct.new(start: start_date, finish: end_date)
end
end
class User
def self.highest_kilometers_within_period period
all.max { |a, b| a.activities.total_distance_between(period)\
<=> b.activities.total_distance_between(period) }
end
end
class Activity
def self.total_distance_between period
between(period).sum(:distance)
end
def self.between period
where(date: period.start..period.finish)
end
end
NB - all. in a class method has replaced scope, this does the scoping of the data, tricky ha. :)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment