Skip to content

Instantly share code, notes, and snippets.

@pmarreck
Created June 18, 2012 14:45
Show Gist options
  • Save pmarreck/2948720 to your computer and use it in GitHub Desktop.
Save pmarreck/2948720 to your computer and use it in GitHub Desktop.
Fully instantiate an ActiveRecord object, complete with ID, without touching the DB
# We had a situation where the site subdomain object had to be read on every single request and were looking for a way to reduce the DB hits, this worked, although you have to be careful to expire the cache properly if the object in question changes
def current_site(memoize = true)
# (assumes "subdomain" and "domain" are available from URL information, this code may need to be tweaked)
@current_site = nil unless memoize
@current_site ||= Site.allocate.init_with('attributes' =>
Rails.cache.fetch("Site#{subdomain}.#{domain}") do
Site.find_by_subdomain_and_domain(domain, subdomain).attributes
end
)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment