Custom Array-like object for partial

I am building a Rails plugin which is somewhat similar to named scopes
and therefore behaves like an array. However it isn't a subclass of
Array, so when one tries to pass it to a partial renderer...

<%= render :partial => @items %>

This does not work because it doesn't know it is a collection and
should be treated as an array. Taking a look at the Rails source both
in master and the 2.3 branch I can see that the NamedScope comparison
is hard-coded.

I think it would be better if ActionView knew nothing of ActiveRecord
here and instead offered some kind of standard that ActiveRecord and
others can follow. This would seem to flow with the more modular
approach that Rails 3 is taking.

I'm willing to write up a patch for this, but I want to get some
discussion going on how best to handle it. One idea is a documented
"collection_for_rails_partial?" method one can define in the object,
but that seems a bit ugly.

Also if there is a current solution (even if it's a hack) to work
around this problem in Rails 2.3 I'm all ears.


Yeah, if I’m not mistaken that’s one of the points of the ActiveORM project.

I see now that the current check is pretty ugly:

if Array === partial_path ||

(defined?(ActiveRecord) &&

(ActiveRecord::Associations::AssociationCollection === partial_path ||

ActiveRecord::NamedScope::Scope === partial_path))

render_partial_collection(options.except(:partial).merge(:collection => partial_path))

How about simply:

if partial_path.respond_to?(:each) and not String === partial_path

Are there use cases where models themselves will respond to “each”, or where this approach could otherwise backfire?

The current plan is to completely remove all AR-specific code from the partial rendering. ActionORM is the first attempt to make that work, and it’s still in progress. Something like Mislav’s solution will probably work.

– Yehuda