Created
November 21, 2011 21:22
-
-
Save mlangenberg/1383983 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
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output: