title: Rails: Run code before ActiveRecord model retrieval
body: <p>Is there a way to run code BEFORE model retrieval? I know about the <strong>after_find</strong> callback, but I need to run before. I'd also like it to run only ONCE per retrieval regardless of the number of records returned. Looking at the RoR source it seems the query is actually executed in <strong>exec_queries</strong>(or <strong>to_a</strong>) in <strong>ActiveRecord::Relation</strong>. Do/Should I override this method to add this hook?</p>
  
  <p>And just in case I'm going about this all wrong, the reason I'm asking is I have an external REST API I am using to retrieve data, but it is too slow to retrieve after every page reload. I was originally using memcached, but I figured I could just use ActiveRecord to cache the data in a database so I can easily query the data and possibly join it with similar data from other REST APIs. I'd like to plug in a callback that would after a certain timeout duration, reload the data from REST before returning ActiveRecord results.</p>
  
  <p>Basically I'm looking for the best way to centralize refreshing my database from another source (REST) instead of cluttering up my controllers or overriding every model accessor that I use (is there a way to override them all easily?). Perhaps the best solution lies here.</p>
  
  <p>It appears all of the built in methods like all, find, first, and last call <strong>apply_finder_options</strong> (and then <strong>where</strong>), but the dynamically created finders (find_by_name, etc) call <strong>find_dynamic_match</strong> which eventually calls <strong>where</strong>. This is what lead me to the <strong>to_a</strong> method on the relation, since it is common and called when the query is actually executed, and not just when building a relation before a query is executed. However getting this low level in into Rails makes me uncomfortable.</p>
  
  <p>It seems like my problem shouldn't be an uncommon one, so perhaps my approach is wrong?</p>
  
  <p>FYI, I'm new to rails and ruby. Thanks!</p>