Skip to content

Instantly share code, notes, and snippets.

@mlangenberg
Created November 21, 2011 21:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mlangenberg/1383983 to your computer and use it in GitHub Desktop.
Save mlangenberg/1383983 to your computer and use it in GitHub Desktop.
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
Copy link
Author

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