Skip to content

Instantly share code, notes, and snippets.

@mlangenberg
Created November 23, 2011 21:19
Show Gist options
  • Save mlangenberg/1389951 to your computer and use it in GitHub Desktop.
Save mlangenberg/1389951 to your computer and use it in GitHub Desktop.
class Api::Post
def self.first
etag = $cache.read('data:etag')
response = fetch_first(etag)
if response == :not_modified
puts 'cache HIT'
else
puts 'cache MISS'
$cache.write 'data:etag', response.first
$cache.write 'data', response.last
end
new(etag)
end
def self.fetch_first(etag)
if etag.nil?
puts 'Fetch XML'
["1449ee0ec320e5bf5ed7a9949d4771d9", "<post>Hallo!</post>"]
else
:not_modified
end
end
attr_reader :cache_key
def initialize(etag)
@cache_key = etag
@document = nil
end
def body
parse if @document.nil? # Lazy-loading
@document.children.first.text
end
def parse
@document = Nokogiri.parse($cache.read('data'))
end
end
<% cache [@post.cache_key, 'author'] %>
<h1><%= @post.author %></h1>
<% end %>
Hello, <%= current_user.name %>, this is not cached.
<% cache [@post.cache_key, 'body'] %>
<p><%= @post.body %></p>
<% end %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment