Module: Monocle::ClassMethods

Defined in:
lib/monocle.rb

Instance Method Summary collapse

Instance Method Details

#monocle_key(*append) ⇒ Object



34
35
36
37
# File 'lib/monocle.rb', line 34

def monocle_key(*append)
  extra = (append.empty?) ? '' : ':' + append.join(':')
  "monocle:#{self.to_s.underscore}" + extra
end

#monocle_options(options = {}) ⇒ Object



39
40
41
# File 'lib/monocle.rb', line 39

def monocle_options(options = {})
  self._monocle_options = self._monocle_options.merge(options)
end

#monocle_views(types = {}) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/monocle.rb', line 43

def monocle_views(types = {})
  self._monocle_view_types = types
  self._monocle_view_types.each do |k,v|
    define_method("#{k}_views_count") do
      self._monocle_redis_connection.hget(self.class.monocle_key(id), self.send("#{k}_views_field")).to_i || 0
    end

    define_method("#{k}_views_field") do
      field = v.call
      field.is_a?(String) ? field : field.to_i
    end

    define_method("#{k}_clicks_count") do
      self._monocle_redis_connection.hget(self.class.monocle_key(id), self.send("#{k}_clicks_field")).to_i || 0
    end

    define_method("#{k}_clicks_field") do
      field = v.call
      field.is_a?(String) ? field : field.to_i
    end
  end
end

#most_viewed_since(since, options = {}) ⇒ Object



74
75
76
77
78
79
80
81
# File 'lib/monocle.rb', line 74

def most_viewed_since(since, options = {})
  options[:limit] ||= 1000
  options[:with_objects] = options.has_key?(:with_objects) ? options[:with_objects] : true

  viewed_by_score = self._monocle_redis_connection.zrevrangebyscore(self.monocle_key('view_counts'), '+inf', '-inf', limit: [0, options[:limit]])
  results = viewed_by_score & recently_viewed_since(since, with_objects: false, limit: options[:limit])
  options[:with_objects] ? results.map { |id| self.find(id) } : results
end

#recently_viewed_since(since, options = {}) ⇒ Object



66
67
68
69
70
71
72
# File 'lib/monocle.rb', line 66

def recently_viewed_since(since, options = {})
  options[:limit] ||= 1000
  options[:with_objects] = options.has_key?(:with_objects) ? options[:with_objects] : true

  results = self._monocle_redis_connection.zrevrangebyscore(self.monocle_key('recently_viewed'), Time.now.to_i, since.to_i, limit:[0, options[:limit]])
  options[:with_objects] ? results.map { |id| self.find(id) } : results
end