Skip to content

Instantly share code, notes, and snippets.

@milushov
Last active December 17, 2015 05:19
Show Gist options
  • Save milushov/5556745 to your computer and use it in GitHub Desktop.
Save milushov/5556745 to your computer and use it in GitHub Desktop.
def week_stat model
period = 7
table = model.name.tableize
from = Time.now.utc.midnight - period.days
query = <<-SQL
select created_at as time, count(*) as count
from #{table}
where created_at > '#{from}'
group by DAYOFWEEK(created_at)
SQL
w_stats = ActiveRecord::Base.connection.select(query)
sparkline = []
today = Time.now.utc
0.upto(period) do |i|
cur_day = today - i.day
res = w_stats.select do |day|
cur_day.beginning_of_day <= day['time'] && day['time'] <= cur_day.end_of_day
end
sparkline.push res.empty? ? 0 : res.first['count']
end
sparkline.reverse
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment