Merge pull request #5056 from ayastreb/drop-fetch

Merge pull request 5056
This commit is contained in:
jekyllbot 2016-07-06 19:34:56 -07:00 committed by GitHub
commit 08b279cbdd
2 changed files with 53 additions and 0 deletions

View File

@ -199,6 +199,17 @@ module Jekyll
end
end
end
# 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
end

42
test/test_drop.rb Normal file
View File

@ -0,0 +1,42 @@
require "helper"
class TestDrop < JekyllUnitTest
context "a document drop" do
setup do
@site = fixture_site({
"collections" => ["methods"]
})
@site.process
@document = @site.collections["methods"].docs.detect do |d|
d.relative_path == "_methods/configuration.md"
end
@drop = @document.to_liquid
end
should "raise KeyError if key is not found and no default provided" do
assert_raises KeyError do
@drop.fetch("not_existing_key")
end
end
should "fetch value without default" do
assert_equal "Jekyll.configuration", @drop.fetch("title")
end
should "fetch default if key is not found" do
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