representable
representable copied to clipboard
Default not working on nested collections
I'm not sure if this applies to properties as well.
Basically we want collections to default to an empty array.
The collections at the base are empty arrays as expected, but the collections inside nested are not.
However we are able to access the collection if it is populated.
Example
collection :collection_1, default: []
nested :nesting do
collection :collection_2, default: []
end
abc = OpenStruct.new.extend(ABCRepresenter)
abc.collection_1 => []
abc.collection_2 => nil
Cheers
I'm guessing its the result of the payload not containing the nested attribute therefore not triggering the nested collection, wondering if there's a way to have it set anyway.
From a use case pov, when I nest something I want the data represented on the base object so I still want that base object to have the default value. Also its too conditional to have the default only happen if the nested appears but not the collection.
For non-nested properties it kind of makes sense, but for nested I think the default should exist.
Thanks
Waaiiit a second... are you talking about rendering or parsing??
Well the default gets set during parsing. I don't use the to_hash rendered result just the represented/openstruct.
Any updates on this?
Just wondering whether this is a design decision or something that you might work on. Just not sure whether I should work on implementing this myself.
Basically I need nested fields to set the default, currently only the non-nested fields get set. The represented variable seems to have it set during parsing, but the end result its not there. Might be something to do with the nested decorator?
This is during parsing, not sure about rendering. I use the built Representable Object (as OpenStruct) rather than the rendered hash. This is with the end goal of using Representable to parse and populate a model from JSON rather than create a representation.
Cheers
Ah, I guess I understand now. If you just extend an object with a representer, the default doesn't get "triggered". A representer's job is solely acting on to_format
and from_format
, and the :default
option is designed for those two operations, only.
So, this is a design decision.
It sounds more like you want coercion as found in virtus, which adds accessor to your model?!