Flexible constant caching in Rails
Submitted by greg on Tue, 07/21/2009 - 17:48
As outlined in By Patrick Reagan's Recipe 61 of the very helpful Advanced Rails Recipes book, it's easy to cache your constants when loading your Rails models, which can help with both performance and speed (and accuracy!) of development. I liked this solution because it's so easy to setup. However, some of my models are better keyed off a different field than name. So I made the below modification to give me the flexibility I needed:
</p>
[geshifilter-pre]module ConstantCache module ClassMethods def caches_constants(field_<script src="http://greghaygood.com/sites/all/modules/tinytinymce/tinymce/jscripts/tiny_mce/themes/advanced/langs/en.js?u" type="text/javascript"><!--mce:0--></script>sym = :name) begin find(:all).each do |instance| key = instance.send field_sym.to_sym const = key.gsub(/\s+/, '_').upcase if const_defined?(const) raise RuntimeError, "Constant #{self.to_s}::#{const} has already been defined" else const_set(const, instance) end end rescue Exception =&gt; e end end end end ActiveRecord::Base.send(:extend, ConstantCache::ClassMethods) [/geshifilter-pre]
<div>
Then in my model, I can just say:
</p> [geshifilter-pre]caches_constants :my_other_key[/geshifilter-pre] <p>
Bookmark/Search this post with

Comments
Post new comment