Skip to content

Instantly share code, notes, and snippets.

@wildfalcon
Created July 21, 2010 10:41
Show Gist options
  • Save wildfalcon/484326 to your computer and use it in GitHub Desktop.
Save wildfalcon/484326 to your computer and use it in GitHub Desktop.
Adding Zeros
# I was dealing with a number of different log methods (per minute, per hour, per day) etc
# Where times with no data were not stored in the database. This was an attempt at getting active record to
# inject zeroed data into to the returned datasets.
#
# It worked, but the experiment was a failure:
# 1) extracting times from the where_values is brittle and will fail often
# 2) It gets applied to all AR models
# 3) It required adding two methods (new_default and period) to the corrospoding AR classes creating too strong coupling
class ActiveRecord::Relation
def with_zeros
start_date = Date.parse(where_values.first.split("'")[1])
end_date = Date.parse(where_values.first.split("'")[3])
puts "Creating values between #{start_date} and #{end_date}"
start_time = Time.utc(start_date.year, start_date.month, start_date.day)
end_time = Time.utc(end_date.year, end_date.month, end_date.day)
puts "We are working with #{self.klass.name} data"
puts "First timestamp is #{start_time.to_time}"
puts "Last timestamp is #{end_time.to_time}"
#Note we assume that this is sorted
data_without_zeros = self.all
data_with_zeros = []
t = start_time
next_index = 0
while t < end_time
if(data_without_zeros[next_index] && (data_without_zeros[next_index].created_at == t))
data_with_zeros << data_without_zeros[next_index]
next_index += 1
else
data_with_zeros << self.klass.new_default(t)
end
t = t + self.klass.period
end
data_with_zeros
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment