Created
March 8, 2012 00:30
-
-
Save russ/1997566 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Feeds | |
module Cache | |
extend ActiveSupport::Concern | |
module InstanceMethods | |
def redis_client | |
uri = URI.parse(ENV["REDISTOGO_URL"] || "http://localhost:6379/") | |
@redis ||= Redis.new(host: uri.host, port: uri.port, password: uri.password) | |
end | |
end | |
def cache_result(*symbols) | |
symbols.each do |symbol| | |
original_method = :"_uncached_#{symbol}" | |
class_eval <<-EOS, __FILE__, __LINE__ + 1 | |
include InstanceMethods | |
alias #{original_method} #{symbol} | |
def #{symbol} | |
key = "feeds:cache:" + self.class.to_s.underscore | |
if cache = redis_client.get(key) | |
JSON.parse(Marshal.load(cache.unpack("m")[0])) | |
else | |
result = #{original_method} | |
redis_client.set(key, [ Marshal.dump(result.to_json) ].pack("m")) | |
result | |
end | |
end | |
EOS | |
end | |
end | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "active_support/all" | |
require File.dirname(__FILE__) + "/../../../lib/feeds/cache" | |
class Redis | |
def initialize(params) | |
end | |
def set(key, value) | |
value | |
end | |
end | |
class TestFeed | |
extend Feeds::Cache | |
def raw_data | |
{ "data" => "special_data" } | |
end | |
cache_result :raw_data | |
end | |
module Feeds | |
describe Cache do | |
it "when there is no cached result, cache the result" do | |
Redis.any_instance.should_receive(:get).and_return(nil) | |
Redis.any_instance.should_receive(:set).and_return(true) | |
TestFeed.new.raw_data.should == { "data" => "special_data" } | |
end | |
it "when is a cached result, return the cache" do | |
Redis.any_instance.should_receive(:get).and_return("BAhJIhx7ImRhdGEiOiJzcGVjaWFsX2RhdGEifQY6BkVG\n") | |
TestFeed.new.raw_data.should == { "data" => "special_data" } | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment