Created
October 10, 2011 05:41
-
-
Save ahcarpenter/1274694 to your computer and use it in GitHub Desktop.
sample ruby code
This file contains 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
#------------------ Misc | |
def clock_in | |
timestamp = Timestamp.new | |
timestamp.user_id = self.id | |
timestamp.time_in = DateTime.now | |
timestamp.save | |
end | |
def clock_out(user_id) | |
timestamp = Timestamp.find_last_by_user_id(user_id) | |
timestamp.time_out = DateTime.now if timestamp.time_out.nil? #accounts for the possibility of the user clicking logout twice | |
timestamp.save | |
end | |
def helpers | |
ActionController::Base.helpers | |
end | |
def readable_last_login!(login) | |
helpers.distance_of_time_in_words(login[0].time_in, login[0].time_out, true) | |
end | |
def readable_all_time_hours!(total_time) #TODO: move to timestamps | |
helpers.time_ago_in_words(Time.now - total_time.seconds, true) | |
end | |
def day_ordinal_suffix(time) #credit: Bay Gross | |
day = time.day | |
if day == 11 or day == 12 | |
return "th" | |
else | |
case day % 10 | |
when 1 then return "st" | |
when 2 then return "nd" | |
when 3 then return "rd" | |
else return "th" | |
end | |
end | |
end | |
#returns text representing the information regarding a user's last login | |
def last_login | |
relevant_timestamps = Timestamp.valid_time_outs #TODO: fetch in batches, throw error if no valid timestamps found "you never logged out!" | |
login = relevant_timestamps.each {|timestamp| return timestamp if (timestamp.user_id == self.id)} #the array should only contain one value, the last_login with a non-null time_out | |
return login[0].time_in.time.strftime("%A") + ", " + MONTHS[login[0].time_in.month-1][1].to_s + " " + login[0].time_in.day.to_s + day_ordinal_suffix(login[0].time_in.day) + login[0].time_in.time.strftime(" at%l:%M%P") + " for " + readable_last_login!(login) + "." | |
end | |
#returns text representing the aggregate time logged by all users -- can be converted to just hours | |
def all_time_hours #TODO: Move to Logins | |
seconds_elapsed = 0 | |
Timestamp.find_each { |timestamp| (seconds_elapsed += (timestamp.time_out - timestamp.time_in)) if !timestamp.time_out.nil?} #TODO: fetch in batches | |
return readable_all_time_hours!(seconds_elapsed) + " logged." | |
end | |
end | |
########################### | |
#TODO: Test performance against against strtime | |
MONTHS=[ | |
[ 1, "January" ], | |
[ 2, "February" ], | |
[ 3, "March" ], | |
[ 4, "April" ], | |
[ 5, "May" ], | |
[ 6, "June" ], | |
[ 7, "July" ], | |
[ 8, "August" ], | |
[ 9, "September" ], | |
[ 10, "October" ], | |
[ 11, "November" ], | |
[ 12, "December" ], | |
] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment