active-hash / active_hash

A readonly ActiveRecord-esque base class that lets you use a hash, a Yaml file or a custom file as the datasource
MIT License
1.2k stars 179 forks source link

Add size method to ActiveHash::Relation #223

Closed sikachu closed 2 years ago

sikachu commented 3 years ago

Starting from Rails 6.1, Action View now tries to call size on collection to find out the collection's size while it's building the cursor. This causes a compatibility issue when you try to render ActiveHash::Relation as a collection object, as AH::R did not respond to #size.

Error message:

ActionView::Template::Error:
  undefined method `size' for #<ActiveHash::Relation:0x00007f9232aed640>
# [GEM_HOME]/actionview-6.1.1/lib/action_view/renderer/collection_renderer.rb:48:in `size'
# [GEM_HOME]/actionview-6.1.1/lib/action_view/renderer/collection_renderer.rb:178:in `collection_with_template'
# [GEM_HOME]/actionview-6.1.1/lib/action_view/renderer/collection_renderer.rb:165:in `block in render_collection'
# [GEM_HOME]/activesupport-6.1.1/lib/active_support/notifications.rb:203:in `block in instrument'
# [GEM_HOME]/activesupport-6.1.1/lib/active_support/notifications/instrumenter.rb:24:in `instrument'
# [GEM_HOME]/activesupport-6.1.1/lib/active_support/notifications.rb:203:in `instrument'
# [GEM_HOME]/actionview-6.1.1/lib/action_view/renderer/collection_renderer.rb:147:in `render_collection'
# [GEM_HOME]/actionview-6.1.1/lib/action_view/renderer/collection_renderer.rb:135:in `render_collection_derive_partial'
# [GEM_HOME]/actionview-6.1.1/lib/action_view/renderer/renderer.rb:90:in `render_partial_to_object'
# [GEM_HOME]/actionview-6.1.1/lib/action_view/renderer/renderer.rb:53:in `render_partial'
# [GEM_HOME]/actionview-6.1.1/lib/action_view/helpers/rendering_helper.rb:45:in `render'

Example code that triggered the error:

render Model.where(params: true)

Related code in Rails: https://github.com/rails/rails/blob/v6.1.1/actionview/lib/action_view/renderer/collection_renderer.rb#L47-L49

In this commit, I also switched count method to use alias_method as both count and size can be defined as an alias for length.

sikachu commented 2 years ago

Looks like this has been fixed by #227, so closing this.