Topic: Statistics Generation

I would love to clean this up:

def last_login_range
  range = {'24hr' => 0, '48hr' => 0, '72hr' => 0, '5days' => 0, '1wk' => 0, '2wk' => 0,                      '1month' => 0, '2months' => 0, '6months' => 0, '1year' => 0}

  for user in @users do
    range['24hr']      += 1 if user.last_login.between?(24.hours.ago, Time.now)
    range['48hr']      += 1 if user.last_login.between?(48.hours.ago, 24.hours.ago)
    range['72hr']      += 1 if user.last_login.between?(72.hours.ago, 48.hours.ago)
    range['5days']     += 1 if user.last_login.between?(5.days.ago, 72.hours.ago)
    range['1wk']          += 1 if user.last_login.between?(1.week.ago, 5.days.ago)
    range['2wk']       += 1    if user.last_login.between?(2.weeks.ago, 1.week.ago )
    range['1month'] += 1 if user.last_login.between?(1.month.ago, 2.weeks.ago)
    range['2months'] += 1 if user.last_login.between?(2.months.ago, 1.month.ago)
    range['6monghts'] += 1 if user.last_login.between?(6.months.ago, 2.months.ago)
    range['1year'] += 1 if user.last_login.between?(5.years.ago, 6.months.ago)
  end
  return range
end

--Any ideas?

Re: Statistics Generation

def last_login_range
    #this can be fairly easily altered to add/remove timestamps
    #you could refactor it out to a controller and pass it as an argument instead
    ranges = {
            '24h' => 24.hours.ago,
            '1d' => 1.days.ago,
            #and so on....
            #you could also do this
            #'In the last day' => 24.hours.ago
        }
   
    #a hash to hold the stats
    stats = Hash.new   
   
    #a placeholder
    bottom_of_range = Time.now   

    #gather stats for the date ranges we want
    ranges.keys.each do |top_of_range|
        #initialize the slot in stats if it is empty
        stats[x] = 0 unless stats[x] != nil

        stats[x] += 1 if user.last_login.between?(top_of_range, bottom_of_range)
    end

    return stats
end


I also think that there might be some way to group and sort using SQL but I'd have to guess and check that a little more than the Ruby code and it probably wouldn't be portable between database engines.

Re: Statistics Generation

Try this:

# user model
def self.count_last_login(from, to = Time.now)
  count(:conditions => { :last_login => from..to })
end

# view:
Users logged in past 24 hours:
<%= User.count_last_login(24.hours.ago) %>

48 hours:
<%= User.count_last_login(48.hours.ago, 24.hours.ago) %>

etc..


That will result in a number of SQL queries, but it's better then fetching all the users.

Railscasts - Free Ruby on Rails Screencasts

Re: Statistics Generation

works like a gem! Thanks!