Search code examples
ruby-on-railschartsreportinggoogle-visualizationsparklines

Get an array containing the number of posts created in the past 2 weeks


I want to create sparklines that illustrate the number of posts created on my blog in the last 2 weeks. To do this, I need to first generate an array that contains the number of posts created on each day during the period in question.

For example, this array:

[40, 18, 0, 2, 39, 37, 22, 25, 30, 60, 36, 5, 2, 2]

generates this sparkline: (I'm using the Googlecharts wrapper around the Google Charts API)

My question is how to create these arrays. Here's what I'm doing now: (I'm using Searchlogic to do the queries, but it should be understandable even if you've never used it)

  history = []
  14.downto(1) do |days_ago|
    history.push(Post.created_at_after((days_ago + 1).day.ago.beginning_of_day).created_at_before((days_ago - 1).days.ago.beginning_of_day).size)
  end

This approach is ugly and slow -- there must be a better way!


Solution

  • This will give you a hash mapping dates to post counts:

    counts = Post.count(
      :conditions => ["created_at >= ?", 14.days.ago],
      :group => "DATE(created_at)"
    )
    

    You can then turn this into an array:

    counts_array = []
    14.downto(1) do |d|
      counts_array << (counts[d.days.ago.to_date.to_s] || 0)
    end