Created
June 18, 2012 14:45
-
-
Save pmarreck/2948720 to your computer and use it in GitHub Desktop.
Fully instantiate an ActiveRecord object, complete with ID, without touching the DB
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
# 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