Skip to content
Browse files

Update caching example in README

  • Loading branch information...
1 parent 0b37d87 commit 721b7f4c52a7ac7422dcfa7e221dbd911d553274 @remiprev committed May 4, 2012
Showing with 22 additions and 26 deletions.
  1. +9 −12 README.md
  2. +13 −14 examples/twitter-search/app.rb
View
21 README.md
@@ -179,22 +179,19 @@ gem "faraday_middleware"
In your Ruby code:
```ruby
-class MyCache
- def initialize
- @cache = {}
- end
-
- def write(key, value)
- @cache[key] = value
+class MyCache < Hash
+ def read(key)
+ if cached = self[key]
+ Marshal.load(cached)
+ end
end
- def read(key)
- @cache[key]
+ def write(key, data)
+ self[key] = Marshal.dump(data)
end
- def fetch(key, &block)
- return value = read(key) if value.nil?
- write key, yield
+ def fetch(key)
+ read(key) || yield.tap { |data| write(key, data) }
end
end
View
27 examples/twitter-search/app.rb
@@ -12,31 +12,30 @@ def on_complete(env)
end
end
-class MyCache
- def initialize
- @cache = {}
- end
-
- def write(key, value)
- @cache[key] = value
+class MyCache < Hash
+ def read(key)
+ if cached = self[key]
+ Marshal.load(cached)
+ end
end
- def read(key)
- @cache[key]
+ def write(key, data)
+ self[key] = Marshal.dump(data)
end
- def fetch(key, &block)
- return value = read(key) if value.nil?
- write key, yield
+ def fetch(key)
+ read(key) || yield.tap { |data| write(key, data) }
end
end
$cache = MyCache.new
# Initialize API
Her::API.setup :base_uri => "http://search.twitter.com" do |builder|
- builder.swap Her::Middleware::FirstLevelParseJSON, TwitterSearchParser
+ builder.use Faraday::Request::UrlEncoded
builder.use FaradayMiddleware::Caching, $cache
+ builder.use TwitterSearchParser
+ builder.use Faraday::Adapter::NetHttp
end
# Define classes
@@ -49,6 +48,6 @@ def self.search(query, attrs={})
end
get "/" do
- @tweets = Tweet.search("github", :rpp => 30)
+ @tweets = Tweet.search("justin bieber", :rpp => 30)
haml :index
end

0 comments on commit 721b7f4

Please sign in to comment.
Something went wrong with that request. Please try again.