Skip to content

@mlangenberg /awesome_cache.rb
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
require 'nokogiri'
class Cache
def initialize
@store = {}
end
def read key
@store[key]
end
def write key, value
@store[key] = value
end
end
$cache = Cache.new
module Api
class Post
def self.first
etag = $cache.read('data:etag')
response = fetch_first(etag)
if response == :not_modified
puts 'cache HIT'
return $cache.read 'data'
else
puts 'cache MISS'
puts 'Parse XML'
post = new(response.last)
data = yield post
$cache.write 'data', data
$cache.write 'data:etag', response.first
return data
end
end
def self.fetch_first(etag)
if etag.nil?
puts 'Fetch XML'
["1449ee0ec320e5bf5ed7a9949d4771d9", "<posts><post>Hello!</post></posts>"]
else
:not_modified
end
end
def initialize(xml)
@doc = Nokogiri.parse(xml)
end
def body
@doc.children.first.text
end
end
end
class Post
def initialize(post)
@post = post
end
def self.first(&block)
Api::Post.first do |post|
puts 'wrap in domain layer'
block.call new(post)
end
end
def body
@post.body
end
end
def render_view
Post.first do |post|
puts 'generate HTML'
"<h1>#{post.body}</h1>"
end
end
3.times do
puts render_view
end
@mlangenberg
Owner

Output:

Fetch XML
cache MISS
Parse XML
wrap in domain layer
generate HTML
    <h1>Hello!</h1>
cache HIT
    <h1>Hello!</h1>
cache HIT
    <h1>Hello!</h1>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.