Collection parsing raises an error if the value is nil
Hi! I'm not sure if this is a bug or if there is some way to deal with it.
Given a representable with a collection inside:
class SongRepresenter < Representable::Decorator
include Representable::JSON
property :title
property :track
collection :composers
end
When trying to parse a Json with collection: [], it works!
pry(main)> hash = {title: "aa", track: "bb", composers: []}
pry(main)> SongRepresenter.new(Song.new).from_json(hash.to_json)
=> #<Song title="aa", track="bb", composers=[]>
But when setting composer: nil, it raises an error (very difficult to understand):
pry(main)> hash = {title: "aa", track: "bb", composers: nil}
pry(main)> SongRepresenter.new(Song.new).from_json(hash.to_json)
NoMethodError: undefined method `each_with_index' for nil:NilClass
from /home/fabioperrella/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/representable-2.3.0/lib/representable/deserializer.rb:86:in `call'
I tried to use render_nil: true, but the same problem occurred.
I got this problem because Rails 4.x is replacing the [] value by nil -> https://github.com/rails/rails/pull/12251#issuecomment-31032624
Is there any option to a collection accept a nil value?
Is this really a bug?
Thanks!
cc @BCecatto
@fabioperrella just stumbled upon this as I have the same issue, is this actually a bug or did you find an option that gets this to work?
Hey @maxemitchell , sorry, but I'm currently completely out of this context and I can't help you with this
@maxemitchell Above error is coming while deserializing given json as we can see from the trace, so you can override parsing phase which happens earlier using reader option 🍻
collection :composers, reader: ->(doc, *) { self.composers = Array(doc[:composers])
Note that this error isn't reproducible on latest v3.1.1 (trace shows v2.3.0 is being used)