Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature: Discard nil value field #425

Merged
merged 10 commits into from
Jul 11, 2024
30 changes: 30 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -694,6 +694,36 @@ _NOTE:_ The field-level setting overrides the global config setting (for the fie

</details>

<details>
<summary>Exclude Fields with nil Values</summary>


By default, fields with `nil` values are included when rendering. You can override this behavior by setting `:exclude_if_nil: true` in the field definition.

Usage:

```ruby
class UserBlueprint < Blueprinter::Base
identifier :uuid

field :name
field :birthday, exclude_if_nil: true
end

user = User.new(name: 'John Doe')
puts UserBlueprint.render(user)
```

Output:

```json
{
"name": "John Doe"
}
```

</details>

<details>
<summary>Custom Formatting for Dates and Times</summary>

Expand Down
6 changes: 5 additions & 1 deletion lib/blueprinter/helpers/base_helpers.rb
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,11 @@ def object_to_hash(object, view_name:, local_options:)
result_hash = view_collection.fields_for(view_name).each_with_object({}) do |field, hash|
next if field.skip?(field.name, object, local_options)

hash[field.name] = field.extract(object, local_options)
value = field.extract(object, local_options)

next if value.nil? && field.options[:exclude_if_nil]

hash[field.name] = value
end
view_collection.transformers(view_name).each do |transformer|
transformer.transform(result_hash, object, local_options)
Expand Down
24 changes: 24 additions & 0 deletions spec/integrations/base_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,30 @@
end
end

context 'Given exclude_if_nil is passed' do
let(:obj) { OpenStruct.new(obj_hash.merge(nil_attribute: nil)) }

context 'and exclude_if_nil is true' do
let(:blueprint) do
Class.new(Blueprinter::Base) do
field :nil_attribute, exclude_if_nil: true
end
end
let(:result) { '{}' }
it { expect(blueprint.render(obj)).to eq(result) }
end

context 'and exclude_if_nil is false' do
let(:blueprint) do
Class.new(Blueprinter::Base) do
field :nil_attribute, exclude_if_nil: false
end
end
let(:result) { '{"nil_attribute":null}' }
it { expect(blueprint.render(obj)).to eq(result) }
end
end
jamesst20 marked this conversation as resolved.
Show resolved Hide resolved

context 'Inside Rails project' do
include FactoryBot::Syntax::Methods
let(:obj) { create(:user) }
Expand Down