Skip to content

Instantly share code, notes, and snippets.

@ktkaushik
Last active December 10, 2015 06:48
Show Gist options
  • Select an option

  • Save ktkaushik/4396357 to your computer and use it in GitHub Desktop.

Select an option

Save ktkaushik/4396357 to your computer and use it in GitHub Desktop.
Converting distance_of_time_in_words back to time
# DOES NOT HANDLE 'half a minute' AND 'about a minute' among others
# dotiw is the distance_of_time_in_words
if dotiw
# split it with ' ' and get an array.
# Your array contains things such as :
# ["1", "year,", "11", "months,", "27", "days,", "13", "hours,", "and", "39", "minutes"]
split_distance_of_time_into_array = dotiw.split(' ')
total_time=0
split_distance_of_time_into_array.each_with_index do |t,index|
# Converting any string into integer with no actual integer value inside would return zero.
if t.to_i.zero?
# If t is 'year' then its predecessor in the array has to be the no of years
count = split_distance_of_time_into_array[index-1].to_i
# t could be 'month', 'months', 'months,' or even 'month,'
# Thus, split it with ','
time_unit = t.split(',').first
end
# Converting the count of whatever time_unit into seconds here
# ex :
# count = 3
# time_unit = month
# 3.months.to_i => 7776000
if t != "and" and t != "and," and !count.nil? and !time_unit.nil?
total_time += count.send(time_unit).to_i
end
end
end
activities = Activity.find_all_by_activity_type('app')
activities.each do |activity|
parsed_info = JSON.parse activity.info
if parsed_info.has_key?("exact_duration")
if parsed_info["exact_duration"].class == Float or parsed_info["exact_duration"].class == Fixnum
dotiw = activity.get_value_from_info('exact_duration')
if dotiw
split_distance_of_time_into_array = dotiw.split(' ')
total_time=0
split_distance_of_time_into_array.each_with_index do |t,index|
if t.to_i.zero?
count = split_distance_of_time_into_array[index-1].to_i
time_unit = t.split(',').first
end
if t != "and" and t != "and," and !count.nil? and !time_unit.nil?
total_time += count.send(time_unit).to_i
end
end
if !total_time.zero?
parsed_info["exact_duration"] = total_time
activity.update_attributes!(info: parsed_info.to_json)
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment