Skip to content

Instantly share code, notes, and snippets.

@leonid-shevtsov
Created April 29, 2010 13:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leonid-shevtsov/383623 to your computer and use it in GitHub Desktop.
Save leonid-shevtsov/383623 to your computer and use it in GitHub Desktop.
# 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