@@ -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 }
0 commit comments