From 3aead1d4a944b7895d9961e6eaff3bae9a9b6e73 Mon Sep 17 00:00:00 2001 From: Anatoliy Yastreb Date: Wed, 6 Jul 2016 11:20:37 +0300 Subject: [PATCH] Imitate fetch method instead of creating real Hash object --- lib/jekyll/drops/drop.rb | 11 +++++++++-- test/test_drop.rb | 8 ++++++++ 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/lib/jekyll/drops/drop.rb b/lib/jekyll/drops/drop.rb index b79544fe..dfb35d20 100644 --- a/lib/jekyll/drops/drop.rb +++ b/lib/jekyll/drops/drop.rb @@ -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 diff --git a/test/test_drop.rb b/test/test_drop.rb index e0f1884c..199e94ab 100644 --- a/test/test_drop.rb +++ b/test/test_drop.rb @@ -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