@@ -14,6 +14,7 @@ def initialize(options = {})
14
14
15
15
@key_formatter = options . fetch ( :key_formatter ) { @@key_formatter ? @@key_formatter . clone : nil }
16
16
@ignore_nil = options . fetch ( :ignore_nil , @@ignore_nil )
17
+ @ignore_block = nil
17
18
18
19
yield self if ::Kernel . block_given?
19
20
end
@@ -106,6 +107,24 @@ def self.key_format(*args)
106
107
@@key_formatter = KeyFormatter . new ( *args )
107
108
end
108
109
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
+
109
128
# If you want to skip adding nil values to your JSON hash. This is useful
110
129
# for JSON clients that don't deal well with nil values, and would prefer
111
130
# not to receive keys which have null values.
@@ -288,11 +307,15 @@ def _key(key)
288
307
def _set_value ( key , value )
289
308
raise NullError . build ( key ) if @attributes . nil?
290
309
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 )
292
311
@attributes = { } if _blank?
293
312
@attributes [ _key ( key ) ] = value
294
313
end
295
314
315
+ def _ignore_value? ( value )
316
+ ( @ignore_nil && value . nil? ) || ( @ignore_block && @ignore_block . call ( value ) )
317
+ end
318
+
296
319
def _map_collection ( collection )
297
320
collection . map do |element |
298
321
_scope { yield element }
0 commit comments