Skip to content

Instantly share code, notes, and snippets.

@jzajpt
Created March 14, 2012 09:07
Show Gist options
  • Save jzajpt/2035255 to your computer and use it in GitHub Desktop.
Save jzajpt/2035255 to your computer and use it in GitHub Desktop.
Classes for pulling statistics data from Rails models
# encoding: utf-8
class Statistics::DailyIterator
def initialize(period_start = nil, period_end = nil)
@period_start = (period_start || 30.days.ago).to_date
@period_end = (period_end || 1.day.ago).to_date
end
def each(&block)
period = @period_start..@period_end
period.map do |date|
period_start = date.midnight
period_end = (date + 1.day).midnight
yield period_start, period_end
end
end
end
# encoding: utf-8
class Statistics::Invoices < Statistics::PeriodMetric
def get_count(period_start, period_end)
# scope on Invoice:
# scope :created_between, ->(from, to){ where(:created_at.gte => from, :created_at.lte => to) }
Invoice.created_between(period_start, period_end).count
end
end
# encoding: utf-8
class Statistics::MonthlyIterator
def initialize(period_start = nil, period_end = nil)
@period_start = period_start || 1.year.ago
@period_end = period_end || (Time.now.beginning_of_month - 1.day)
end
def each(&block)
period = @period_end - @period_start
number_of_months = period / 1.month
number_of_months.round.times.map do |i|
period_start = (@period_start + i.months).beginning_of_month
period_end = (@period_start + i.months).end_of_month
yield period_start, period_end
end
end
end
# encoding: utf-8
class Statistics::PeriodMetric
def self.daily_data
metric = self.new
periods = Statistics::DailyIterator.new
periods.each do |period_start, period_end|
count = metric.get_count period_start, period_end
[period_start, count]
end
end
def self.monthly_data
metric = self.new
periods = Statistics::MonthlyIterator.new
periods.each do |period_start, period_end|
count = metric.get_count period_start, period_end
[period_start, count]
end
end
def get_count(period_start, period_end)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment