Class: Fatboy::TimeBasedPopularity

Inherits:
Object
  • Object
show all
Defined in:
lib/fatboy/time_based_popularity.rb

Overview

TimeBasedPopularity measures the popularity based on a set period of time. You should probably never initialize this yourself.

Instance Method Summary collapse

Constructor Details

#initialize(redis, store) ⇒ TimeBasedPopularity

What redis to look in, and what sorted set we're using. Probably don't ever initialize this yourself.


10
11
12
13
# File 'lib/fatboy/time_based_popularity.rb', line 10

def initialize(redis, store)
  @redis = redis
  @store = store
end

Instance Method Details

#enumeratorObject

Get an enumerator of all viewed items, as a Fatboy::ViewedItem, in rank order. Pretty useful for lazy operations and such.


18
19
20
21
22
# File 'lib/fatboy/time_based_popularity.rb', line 18

def enumerator
  Enumerator.new(size) do |yielder|
    range(0..(size-1)).each{|x| yielder.yield x}
  end
end

#leastObject

Get the least viewed item. Returns a Fatboy::ViewedItem


32
33
34
# File 'lib/fatboy/time_based_popularity.rb', line 32

def least
  range(-1..-2).first
end

#mostObject

Get the most viewed item. Returns a Fatboy::ViewedItem


26
27
28
# File 'lib/fatboy/time_based_popularity.rb', line 26

def most
  range(0..1).first
end

#range(rng) ⇒ Object

Specify a range of ranks, and gets them. Returns an array of Fatboy::ViewedItem


45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/fatboy/time_based_popularity.rb', line 45

def range(rng)
  start = rng.first
  stop = rng.last
  ##
  # Build up a list of pairs: [id, score]
  pairs = @redis.zrevrange(@store, start, stop, withscores: true)
  ##
  # Get rid of nils, zip up list with range of rank
  triplets = pairs.reject{|p| !p}.zip(start..stop)
  # After the zip, we have [[[id, score], rank], [[id, score], rank]]
  # So we flatten out the inner arrays, giving us
  # [[id, score, rank], [id, score, rank]]
  triplets.map!(&:flatten)
  ##
  # Use the array splat to more easily pass in the 3 arguments
  triplets.map{|trip| Fatboy::ViewedItem.new(*trip)}
end

#sizeObject

Get the total number of items viewed.


38
39
40
# File 'lib/fatboy/time_based_popularity.rb', line 38

def size
  @redis.zcard(@store)
end