Skip to content

Commit

Permalink
Update caching example in README
Browse files Browse the repository at this point in the history
  • Loading branch information
remi committed May 4, 2012
1 parent 0b37d87 commit 721b7f4
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 26 deletions.
21 changes: 9 additions & 12 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
27 changes: 13 additions & 14 deletions examples/twitter-search/app.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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.