diff --git a/lib/queryable_hash.rb b/lib/queryable_hash.rb index dab4ae5..1235f75 100644 --- a/lib/queryable_hash.rb +++ b/lib/queryable_hash.rb @@ -3,7 +3,7 @@ require_relative "queryable_hash/wrapper" module QueryableHash - def self.wrap(hash) - Wrapper.new hash + def self.wrap(hash, **args) + Wrapper.new hash, **args end end diff --git a/lib/queryable_hash/version.rb b/lib/queryable_hash/version.rb index 6bc53af..cb519e4 100644 --- a/lib/queryable_hash/version.rb +++ b/lib/queryable_hash/version.rb @@ -1,3 +1,3 @@ module QueryableHash - VERSION = "0.0.2" + VERSION = "0.0.3" end diff --git a/lib/queryable_hash/wrapper.rb b/lib/queryable_hash/wrapper.rb index 4f489df..a99bd6b 100644 --- a/lib/queryable_hash/wrapper.rb +++ b/lib/queryable_hash/wrapper.rb @@ -2,9 +2,12 @@ module QueryableHash class Wrapper < SimpleDelegator + attr_reader :nil_value, :raise_when_nil - def initialize(hash) + def initialize(hash, nil_value: nil, raise_when_nil: false) @original_hash = hash + @nil_value = nil_value + @raise_when_nil = raise_when_nil super hash end @@ -19,7 +22,10 @@ def find_all(*queries, nil_value: nil) end end - def find_first(*queries, nil_value: nil, raise_when_nil: false) + def find_first(*queries, nil_value: nil, raise_when_nil: nil) + nil_value = @nil_value if nil_value.nil? + raise_when_nil = @raise_when_nil if raise_when_nil.nil? + first = find_all(*queries, nil_value: nil_value).find do |result| result != nil_value end diff --git a/test/wrapper_test.rb b/test/wrapper_test.rb index 4e7d523..c9467e8 100644 --- a/test/wrapper_test.rb +++ b/test/wrapper_test.rb @@ -63,11 +63,17 @@ class QueryableHashTest < PryTest::Test assert @queryable.find_first(query).nil? end - test "find_first with missing key and nil value" do + test "find_first with missing key and nil_value" do query = "nate.this.key.does.not.exist" assert @queryable.find_first(query, nil_value: "missing") == "missing" end + test "find_first with missing key and nil_value set by instance" do + query = "nate.this.key.does.not.exist" + queryable = QueryableHash.wrap(@data, nil_value: "missing") + assert queryable.find_first(query) == "missing" + end + test "find_first with multiple queries some invalid" do term = @queryable.find_first( "glossary.div.list.entry.term", @@ -79,7 +85,7 @@ class QueryableHashTest < PryTest::Test assert term == "Standard Generalized Markup Language" end - test "find_first with raise" do + test "find_first with raise_when_nil" do query = "nate.this.key.does.not.exist" begin @queryable.find_first(query, raise_when_nil: true) @@ -89,6 +95,16 @@ class QueryableHashTest < PryTest::Test assert e end + test "find_first with raise_when_nil set by instance" do + query = "nate.this.key.does.not.exist" + begin + queryable = QueryableHash.wrap(@data, raise_when_nil: true) + queryable.find_first(query) + rescue NotFoundError => e + end + assert e + end + test "to_hash" do assert @queryable.to_hash == @data end