Flexible constant caching in Rails

Tagged:

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&#10;  module ClassMethods&#10;    def caches_constants(field_&lt;script src=&quot;http://greghaygood.com/sites/all/modules/tinytinymce/tinymce/jscripts/tiny_mce/themes/advanced/langs/en.js?u&quot; type=&quot;text/javascript&quot;&gt;&lt;!--mce:0--&gt;&lt;/script&gt;sym = :name)&#10;      begin&#10;        find(:all).each do |instance|&#10;          key = instance.send field_sym.to_sym&#10;          const = key.gsub(/\s+/, &#039;_&#039;).upcase&#10;          if const_defined?(const)&#10;            raise RuntimeError,&#10;            &quot;Constant #{self.to_s}::#{const} has already been defined&quot;&#10;          else&#10;            const_set(const, instance)&#10;          end&#10;        end&#10;      rescue Exception =&amp;gt; e&#10;      end&#10;    end&#10;  end&#10;end&#10;ActiveRecord::Base.send(:extend, ConstantCache::ClassMethods)&#10;&#10;[/geshifilter-pre]
<div>

 

Then in my model, I can just say:

</p>
[geshifilter-pre]caches_constants :my_other_key[/geshifilter-pre]
<p>

 

Comments

Post new comment

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <pre>, <shell>, <c>, <drupal6>, <java>, <javascript>, <objc>, <perl>, <php>, <python>, <rails>, <ruby>, <sql>, <xmlcode>. The supported tag styles are: <foo>, [foo].

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.