Module: ShareCounts::Caching

Included in:
ShareCounts, Reddit
Defined in:
lib/share_counts/caching.rb

Instance Method Summary collapse

Instance Method Details

#cache_enabled?Boolean

Returns true if the Redis cache store has been initialised

Returns:

  • (Boolean)


10
11
12
# File 'lib/share_counts/caching.rb', line 10

def cache_enabled?
  !$share_counts_cache.nil?
end

#cachedObject

Returns the cached share counts available for each URL, in the format

{

"URL 1": {
  :reddit      => N, 
  :digg        => N, 
  :twitter     => N, 
  :facebook    => N, 
  :fblike      => N, 
  :linkedin    => N, 
  :googlebuzz  => N, 
  :stumbleupon => N
},

"URL 2": {
  ...
}

}



50
51
52
53
54
55
56
57
58
# File 'lib/share_counts/caching.rb', line 50

def cached
  urls = ($share_counts_cache || {}).keys.select{|k| k =~ /^ShareCounts/ }.inject({}) do |result, key|
    data = key.split("||"); network = data[1]; url = data[2]; 
    count = from_redis("ShareCounts||#{network}||#{url}")
    (result[url] ||= {})[network.to_sym] = count unless ["all", "fball"].include? network
    result
  end
  urls
end

#clear_cacheObject

Removes from Redis cache store all the keys used by ShareCounts.



22
23
24
25
# File 'lib/share_counts/caching.rb', line 22

def clear_cache
  ($share_counts_cache || {}).keys.select{|cache_key| cache_key =~ /^ShareCounts/ }.each{|cache_key| 
    $share_counts_cache.del cache_key}
end

#use_cache(*args) ⇒ Object

Enables caching with Redis.

By default, it connects to 127.0.0.1:6379, but it is also possible to specify in the arguments :host, :port the connection details.

If the application using this gem is already using Redis too, with the “redis” gem, it is possible to use the existing instance of Redis by either setting the :redist_store argument or by setting the global variable $share_counts_cache first.



74
75
76
77
78
# File 'lib/share_counts/caching.rb', line 74

def use_cache *args
  arguments = args.inject({}) { |r, c| r.merge(c) }
  $share_counts_cache ||= arguments[:redis_store] || 
    Redis.new(:host => arguments[:host] || "127.0.0.1", :port => arguments[:port] || "6379")  
end