Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optionally raise on empty hash filter definitions #158

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions lib/mutations.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
4 changes: 4 additions & 0 deletions lib/mutations/hash_filter.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
22 changes: 20 additions & 2 deletions spec/hash_filter_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down