diff --git a/lib/mutations.rb b/lib/mutations.rb index be0a856..2dd8ba7 100644 --- a/lib/mutations.rb +++ b/lib/mutations.rb @@ -41,7 +41,16 @@ def cache_constants=(val) def cache_constants? @cache_constants end + + def raise_on_empty_hash_filter=(val) + @raise_on_empty_hash_filter = val + end + + def raise_on_empty_hash_filter + @raise_on_empty_hash_filter + end end end Mutations.cache_constants = true +Mutations.raise_on_empty_hash_filter = false diff --git a/lib/mutations/hash_filter.rb b/lib/mutations/hash_filter.rb index 5f22680..1f0d193 100644 --- a/lib/mutations/hash_filter.rb +++ b/lib/mutations/hash_filter.rb @@ -23,6 +23,10 @@ def initialize(opts = {}, &block) @required_inputs = {} @current_inputs = @required_inputs + if Mutations.raise_on_empty_hash_filter && !block_given? + raise ArgumentError.new("Hash parameter can't be created without passing the block") + end + if block_given? instance_eval(&block) end diff --git a/spec/hash_filter_spec.rb b/spec/hash_filter_spec.rb index a1fef96..3d50a62 100644 --- a/spec/hash_filter_spec.rb +++ b/spec/hash_filter_spec.rb @@ -105,6 +105,24 @@ def input.to_hash assert_equal ({"baz" => :integer}), errors.symbolic end + it "allows empty hash definitions" do + Mutations::HashFilter.new + # the fact that we're here means it didn't raise + end + + describe "with raise_on_empty_hash_filter=true" do + it "raises for empty hash definition" do + begin + old_value = Mutations.raise_on_empty_hash_filter + Mutations.raise_on_empty_hash_filter = true + + assert_raises(ArgumentError) { Mutations::HashFilter.new } + ensure + Mutations.raise_on_empty_hash_filter = old_value + end + end + end + describe "optional params and nils" do it "bar is optional -- it works if not passed" do hf = Mutations::HashFilter.new do @@ -167,7 +185,7 @@ def input.to_hash assert_equal ({"foo" => "bar"}), filtered assert_equal nil, errors end - + it "bar is optional -- discards empty if it needs to be stripped" do hf = Mutations::HashFilter.new do required do @@ -182,7 +200,7 @@ def input.to_hash assert_equal ({"foo" => "bar"}), filtered assert_equal nil, errors end - + it "bar is optional -- don't discard empty if it's spaces but stripping is off" do hf = Mutations::HashFilter.new do required do