Permalink
Browse files

Added configuration option to exclude nil values

  • Loading branch information...
1 parent 233477d commit 7fb23caf0c5b5eed46b2eaa1c007d755b71d2004 @oharsta oharsta committed Dec 16, 2013
Showing with 35 additions and 0 deletions.
  1. +1 −0 .gitignore
  2. +8 −0 lib/rabl/builder.rb
  3. +2 −0 lib/rabl/configuration.rb
  4. +13 −0 test/builder_test.rb
  5. +11 −0 test/configuration_test.rb
View
@@ -5,3 +5,4 @@ Gemfile.lock
pkg/*
fixtures/rails2/log/*.log
tags
+.idea
View
@@ -45,6 +45,7 @@ def compile_hash(options={})
wrap_result(options[:root_name])
replace_nil_values if Rabl.configuration.replace_nil_values_with_empty_strings
+ remove_nil_values if Rabl.configuration.exclude_nil_values
# Return Results
@_root_name ? { @_root_name => @_result } : @_result
@@ -57,6 +58,13 @@ def replace_nil_values
end
end
+ def remove_nil_values
+ @_result = @_result.inject({}) do |hash, (k, v)|
+ hash[k] = v unless v.nil?
+ hash
+ end
+ end
+
def wrap_result(root_name)
if root_name.present?
@_root_name = root_name
@@ -48,6 +48,7 @@ class Configuration
attr_accessor :raise_on_missing_attribute
attr_accessor :perform_caching
attr_accessor :replace_nil_values_with_empty_strings
+ attr_accessor :exclude_nil_values
DEFAULT_XML_OPTIONS = { :dasherize => true, :skip_types => false }
@@ -73,6 +74,7 @@ def initialize
@cache_engine = Rabl::CacheEngine.new
@perform_caching = false
@replace_nil_values_with_empty_strings = false
+ @exclude_nil_values = false
end
# @return The JSON engine used to encode Rabl templates into JSON
View
@@ -55,6 +55,19 @@
Rabl.configuration.replace_nil_values_with_empty_strings = false
end
end
+
+ context "when nil values are excluded" do
+ setup do
+ Rabl.configuration.exclude_nil_values = true
+ builder({ :attributes => { :name => {} } })
+ end
+ asserts "that an nil attribute is not returned" do
+ topic.build(User.new(:name => nil))
+ end.equivalent_to({ })
+ teardown do
+ Rabl.configuration.exclude_nil_values = false
+ end
+ end
end
context "#attribute" do
@@ -14,6 +14,7 @@
asserts(:json_engine).equals { json_engine }
asserts(:cache_engine).is_a?(Rabl::CacheEngine)
asserts(:replace_nil_values_with_empty_strings).equals false
+ asserts(:exclude_nil_values).equals false
end
context 'custom JSON engine configured as Symbol' do
@@ -55,4 +56,14 @@
asserts(:replace_nil_values_with_empty_strings).equals true
end # replace nil values with empty strings
+
+ context 'exclude nil values' do
+ setup do
+ Rabl.configure do |c|
+ c.exclude_nil_values = true
+ end
+ end
+
+ asserts(:exclude_nil_values).equals true
+ end # exclude nil values
end

0 comments on commit 7fb23ca

Please sign in to comment.