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

ignore! function added #361

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 24 additions & 1 deletion lib/jbuilder.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ def initialize(options = {})

@key_formatter = options.fetch(:key_formatter){ @@key_formatter ? @@key_formatter.clone : nil}
@ignore_nil = options.fetch(:ignore_nil, @@ignore_nil)
@ignore_block = nil

yield self if ::Kernel.block_given?
end
Expand Down Expand Up @@ -106,6 +107,24 @@ def self.key_format(*args)
@@key_formatter = KeyFormatter.new(*args)
end

# If you want to skip adding some values to your JSON hash like empty string
# or empty array, you can pass a block.
#
# Example:
# json.ignore! { |value| value.nil? }
# json.id User.new.id
# json.email ''
# {"emails" : '' }
#
# json.ignore! { |value| value.nil? || (value.respond_to?(:empty) && value.empty?) }
# json.id User.new.id
# json.email ''
# { }
#
def ignore!(&block)
@ignore_block = block
end

# If you want to skip adding nil values to your JSON hash. This is useful
# for JSON clients that don't deal well with nil values, and would prefer
# not to receive keys which have null values.
Expand Down Expand Up @@ -288,11 +307,15 @@ def _key(key)
def _set_value(key, value)
raise NullError.build(key) if @attributes.nil?
raise ArrayError.build(key) if ::Array === @attributes
return if @ignore_nil && value.nil? or _blank?(value)
return if _ignore_value?(value) or _blank?(value)
@attributes = {} if _blank?
@attributes[_key(key)] = value
end

def _ignore_value?(value)
(@ignore_nil && value.nil?) || (@ignore_block && @ignore_block.call(value))
end

def _map_collection(collection)
collection.map do |element|
_scope{ yield element }
Expand Down
11 changes: 11 additions & 0 deletions test/jbuilder_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -603,6 +603,17 @@ class JbuilderTest < ActiveSupport::TestCase
assert_equal ['name', 'dne'], result.keys
end

test 'ignore! with block' do
result = jbuild do |json|
json.ignore! { |value| value.blank? }
json.name 'Bob'
json.list []
json.email ''
json.dne nil
end
assert_equal ['name'], result.keys
end

test 'default ignore_nil!' do
Jbuilder.ignore_nil

Expand Down