Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
class MyView < Mustache
def cache_by_user_id
lambda do |text|
cache_key = "user:#{current_user.id}"
if value = $cache.get(cache_key)
value
else
rendered = render(text)
$cache.set(cache_key, rendered)
rendered
end
end
end
end
# assumes $cache.set returns the value that is set, which seems sensible.
def $cache.fetch(key)
get(key) || set(key, yield)
end
class MyView < Mustache
def cache_by_user_id
lambda { |text| $cache.fetch("user:#{current_user.id}"){ render(text) } }
end
end
@reinh

This comment has been minimized.

Copy link
Owner Author

commented May 18, 2010

if $cache had a Hashlike interface, you could also do:

def cache_by_user_id
  lambda { |text| $cache["user:#{current_user.id}"] ||= render(text) }
end

The ||= short-circuits, preventing render(text) from being called if there's a cache hit.

Ruby is so expressive for this sort of problem.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.