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:

  1. </p>
  2. <pre>module ConstantCache
  3. module ClassMethods
  4. 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)
  5. begin
  6. find(:all).each do |instance|
  7. key = instance.send field_sym.to_sym
  8. const = key.gsub(/\s+/, '_').upcase
  9. if const_defined?(const)
  10. raise RuntimeError,
  11. "Constant #{self.to_s}::#{const} has already been defined"
  12. else
  13. const_set(const, instance)
  14. end
  15. end
  16. rescue Exception =&gt; e
  17. end
  18. end
  19. end
  20. end
  21. ActiveRecord::Base.send(:extend, ConstantCache::ClassMethods)
  22.  
  23. </pre>
  24. <div>

 

Then in my model, I can just say:

  1. </p>
  2. <pre>caches_constants :my_other_key</pre>
  3. <p>

 

Comments

Post new comment

TEXTAREA ID: edit-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>, <c>, <drupal6>, <java>, <javascript>, <objc>, <perl>, <php>, <python>, <rails>, <ruby>, <sql>, <xmlcode>. Beside the tag style "<foo>" it is also possible to use "[foo]".

More information about formatting options

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