From 23e05c03792ff1b6f7cd7101566883753c01c5eb Mon Sep 17 00:00:00 2001 From: Abhishek Kumar Date: Sun, 9 Oct 2016 03:41:37 +0530 Subject: [PATCH] ignore! function added --- lib/jbuilder.rb | 25 ++++++++++++++++++++++++- test/jbuilder_test.rb | 11 +++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/lib/jbuilder.rb b/lib/jbuilder.rb index c330532..c38c5a7 100644 --- a/lib/jbuilder.rb +++ b/lib/jbuilder.rb @@ -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 @@ -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. @@ -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 } diff --git a/test/jbuilder_test.rb b/test/jbuilder_test.rb index 2257fb6..1bc3c94 100644 --- a/test/jbuilder_test.rb +++ b/test/jbuilder_test.rb @@ -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