title: How do I modify Rails ActiveRecord query results before returning?
body: <p>I have a table with data that needs to be updated at run-time by additional data from an external service.  What I'd like to do is something like this:</p>
  
  <pre><code>MyModel.some_custom_scope.some_other_scope.enhance_with_external_data.each do |object|
    puts object.some_attribute_from_external_data_source
  end
  </code></pre>
  
  <p>Even if I can't use this exact syntax, I would like the end result to respect any scopes I may use.  I've tried this:</p>
  
  <pre><code>def self.enhance_with_external_data
    external_data = get_external_data
    Enumerator.new do |yielder|
      # mimick some stuff I saw in ActiveRecord and don't quite understand:
      relation.to_a.each do |obj|
        update_obj_with_external_data(obj)
        yielder.yield(obj)
      end
    end
  end
  </code></pre>
  
  <p>This mostly works, except it doesn't respect any previous scopes that were applied, so if I do this:</p>
  
  <pre><code>MyModel.some_custom_scope.some_other_scope.enhance_with_external_data
  </code></pre>
  
  <p>It gives back ALL MyModels, not just the ones scoped by some_custom_scope and some_other_scope.</p>
  
  <p>Hopefully what I'm trying to do makes sense.  Anyone know how to do it, or am I trying to put a square peg in a round hole?</p>