提交 cafed35b 编写于 作者: S Sean Griffin

Add tests for `TypeMap#fetch` and push up to `TypeMap`

It doesn't make sense for the subclass to implement this method, and not
have it on the parent. We can also DRY up the implementation of
`#lookup` to be defined in terms of fetch, which will give us a single
point of entry
上级 e0c93875
......@@ -3,10 +3,6 @@ module Type
class HashLookupTypeMap < TypeMap # :nodoc:
delegate :key?, to: :@mapping
def lookup(type, *args)
@mapping.fetch(type, proc { default_value }).call(type, *args)
end
def fetch(type, *args, &block)
@mapping.fetch(type, block).call(type, *args)
end
......
......@@ -6,6 +6,10 @@ def initialize
end
def lookup(lookup_key, *args)
fetch(lookup_key, *args) { default_value }
end
def fetch(lookup_key, *args)
matching_pair = @mapping.reverse_each.detect do |key, _|
key === lookup_key
end
......@@ -13,7 +17,7 @@ def lookup(lookup_key, *args)
if matching_pair
matching_pair.last.call(lookup_key, *args)
else
default_value
yield lookup_key, *args
end
end
......
......@@ -124,6 +124,21 @@ def test_lookup_non_strings
assert_equal mapping.lookup(3), 'string'
assert_kind_of Type::Value, mapping.lookup(4)
end
def test_fetch
mapping = TypeMap.new
mapping.register_type(1, "string")
assert_equal "string", mapping.fetch(1) { "int" }
assert_equal "int", mapping.fetch(2) { "int" }
end
def test_fetch_yields_args
mapping = TypeMap.new
assert_equal "foo-1-2-3", mapping.fetch("foo", 1, 2, 3) { |*args| args.join("-") }
assert_equal "bar-1-2-3", mapping.fetch("bar", 1, 2, 3) { |*args| args.join("-") }
end
end
end
end
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册