Accept an option 'default' to allow setting default serialized field value if null#115
Accept an option 'default' to allow setting default serialized field value if null#115AllPurposeName merged 3 commits intomasterfrom
Conversation
…for field if null
|
|
||
| def extract(association_name, object, local_options, options={}) | ||
| value = @extractor.extract(association_name, object, local_options, options) | ||
| value = @extractor.extract(association_name, object, local_options, options.except(:default)) |
There was a problem hiding this comment.
Why do you need to do except(:default)?
There was a problem hiding this comment.
I need to except(:default) here, because otherwise, when it makes the call through to the AutoExtractor, the AutoExtractor (with these changes) would then return the default value instead of nil. Then the association extractor would not pass the return options[:default] if value.nil? step and it would go on to call options[:blueprint].prepare(value, view_name: view, local_options: local_options). You can verify that this would fail the test for default association values.
Another option (which is closer to what you are describing) would be something like this:
def extract(association_name, object, local_options, options={})
value = @extractor.extract(association_name, object, local_options, options)
if (options.key?(:default) || value.nil?)
return value
else
view = options[:view] || :default
options[:blueprint].prepare(value, view_name: view, local_options: local_options)
end
endThoughts?
There was a problem hiding this comment.
OHH I see ok nevermind. I think what you have is fine.
| def extract(association_name, object, local_options, options={}) | ||
| value = @extractor.extract(association_name, object, local_options, options) | ||
| value = @extractor.extract(association_name, object, local_options, options.except(:default)) | ||
| return options[:default] if value.nil? |
There was a problem hiding this comment.
Can we just let the AutoExtractor deal with the options[:default] stuff? And take it out of here?
There was a problem hiding this comment.
Yeah I proposed an alternative solution above that let's the AutoExtractor do all the work necessary for defaults.
Included in the PR
For fields that have a value of nil, blueprinter serializes to
nullby default. This PR adds an ability to add adefaultoption to blueprinter fields which can be used as the serialized value instead of null.Before
UserBlueprint.render(user)renders{ "id": 1, "first_name": null }After
UserBlueprint.render(user)renders{ "id": 1, "first_name": "N/A" }Aims to address: #114