Skip to content

Commit 23e05c0

Browse files
committed
ignore! function added
1 parent 003a369 commit 23e05c0

File tree

2 files changed

+35
-1
lines changed

2 files changed

+35
-1
lines changed

lib/jbuilder.rb

+24-1
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ def initialize(options = {})
1414

1515
@key_formatter = options.fetch(:key_formatter){ @@key_formatter ? @@key_formatter.clone : nil}
1616
@ignore_nil = options.fetch(:ignore_nil, @@ignore_nil)
17+
@ignore_block = nil
1718

1819
yield self if ::Kernel.block_given?
1920
end
@@ -106,6 +107,24 @@ def self.key_format(*args)
106107
@@key_formatter = KeyFormatter.new(*args)
107108
end
108109

110+
# If you want to skip adding some values to your JSON hash like empty string
111+
# or empty array, you can pass a block.
112+
#
113+
# Example:
114+
# json.ignore! { |value| value.nil? }
115+
# json.id User.new.id
116+
# json.email ''
117+
# {"emails" : '' }
118+
#
119+
# json.ignore! { |value| value.nil? || (value.respond_to?(:empty) && value.empty?) }
120+
# json.id User.new.id
121+
# json.email ''
122+
# { }
123+
#
124+
def ignore!(&block)
125+
@ignore_block = block
126+
end
127+
109128
# If you want to skip adding nil values to your JSON hash. This is useful
110129
# for JSON clients that don't deal well with nil values, and would prefer
111130
# not to receive keys which have null values.
@@ -288,11 +307,15 @@ def _key(key)
288307
def _set_value(key, value)
289308
raise NullError.build(key) if @attributes.nil?
290309
raise ArrayError.build(key) if ::Array === @attributes
291-
return if @ignore_nil && value.nil? or _blank?(value)
310+
return if _ignore_value?(value) or _blank?(value)
292311
@attributes = {} if _blank?
293312
@attributes[_key(key)] = value
294313
end
295314

315+
def _ignore_value?(value)
316+
(@ignore_nil && value.nil?) || (@ignore_block && @ignore_block.call(value))
317+
end
318+
296319
def _map_collection(collection)
297320
collection.map do |element|
298321
_scope{ yield element }

test/jbuilder_test.rb

+11
Original file line numberDiff line numberDiff line change
@@ -603,6 +603,17 @@ class JbuilderTest < ActiveSupport::TestCase
603603
assert_equal ['name', 'dne'], result.keys
604604
end
605605

606+
test 'ignore! with block' do
607+
result = jbuild do |json|
608+
json.ignore! { |value| value.blank? }
609+
json.name 'Bob'
610+
json.list []
611+
json.email ''
612+
json.dne nil
613+
end
614+
assert_equal ['name'], result.keys
615+
end
616+
606617
test 'default ignore_nil!' do
607618
Jbuilder.ignore_nil
608619

0 commit comments

Comments
 (0)