Imitate fetch method instead of creating real Hash object

This commit is contained in:
Anatoliy Yastreb 2016-07-06 11:20:37 +03:00
parent 72d49490d2
commit 3aead1d4a9
2 changed files with 17 additions and 2 deletions

View File

@ -200,8 +200,15 @@ module Jekyll
end
end
def fetch(*args, &block)
to_h.fetch(*args, &block)
# Imitate Hash.fetch method in Drop
#
# Returns value if key is present in Drop, otherwise returns default value
# KeyError is raised if key is not present and no default value given
def fetch(key, default = nil, &block)
return self[key] if key?(key)
raise KeyError, %(key not found: "#{key}") if default.nil? && block.nil?
return yield(key) unless block.nil?
return default unless default.nil?
end
end
end

View File

@ -27,8 +27,16 @@ class TestDrop < JekyllUnitTest
assert_equal "default", @drop.fetch("not_existing_key", "default")
end
should "fetch default boolean value correctly" do
assert_equal false, @drop.fetch("bar", false)
end
should "fetch default value from block if key is not found" do
assert_equal "default bar", @drop.fetch("bar") { |el| "default #{el}" }
end
should "fetch default value from block first if both argument and block given" do
assert_equal "baz", @drop.fetch("bar", "default") { "baz" }
end
end
end