Last active
December 17, 2015 05:19
-
-
Save milushov/5556745 to your computer and use it in GitHub Desktop.
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
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