Created
April 29, 2010 13:46
-
-
Save leonid-shevtsov/383623 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
# put this into yer initializers | |
# | |
# class Ad < ActiveRecord::Base | |
# belongs_to :city | |
# belongs_to :color | |
# cache_title :city, :color | |
# end | |
# | |
# then Ad.first.city_title | |
class ActiveRecord::Base | |
def self.cache_title(*associations) | |
self.class_eval do | |
associations.each do |association| | |
#TODO is there a better way to do this? | |
association_class = self.new.send('build_'+association.to_s).class | |
association_cache_name = association_class.to_s + '_titles' | |
unless association_class.respond_to? 'cached_titles' | |
(class << association_class; self; end).send(:define_method, :cached_titles) do | |
Rails.cache.fetch(association_cache_name) do | |
titles = {} | |
association_class.all.each do |object| | |
titles[object.id] = object.title | |
end | |
titles | |
end | |
end | |
end | |
define_method (association.to_s + '_title') do | |
association_class.cached_titles[self.send(association.to_s + '_id')] | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment