diff --git a/History.markdown b/History.markdown index f6bfd36..df2b8e3 100644 --- a/History.markdown +++ b/History.markdown @@ -1,5 +1,7 @@ ## HEAD +* Guard against arrays in subhashes #197 + ## 2.2.1 * Convert template logic to a Liquid Drop (significant performance improvement) (#184) diff --git a/lib/jekyll-seo-tag/drop.rb b/lib/jekyll-seo-tag/drop.rb index a0c426a..06fe3a2 100644 --- a/lib/jekyll-seo-tag/drop.rb +++ b/lib/jekyll-seo-tag/drop.rb @@ -55,8 +55,8 @@ module Jekyll seo_name elsif !homepage_or_about? nil - elsif site["social"] && site["social"]["name"] - format_string site["social"]["name"] + elsif site_social["name"] + format_string site_social["name"] elsif site_title format_string site_title end @@ -95,8 +95,8 @@ module Jekyll def date_modified @date_modified ||= begin - date = if page["seo"] && page["seo"]["date_modified"] - page["seo"]["date_modified"] + date = if page_seo["date_modified"] + page_seo["date_modified"] elsif page["last_modified_at"] page["last_modified_at"].to_liquid else @@ -112,8 +112,8 @@ module Jekyll def type @type ||= begin - if page["seo"] && page["seo"]["type"] - page["seo"]["type"] + if page_seo["type"] + page_seo["type"] elsif homepage_or_about? "WebSite" elsif page["date"] @@ -126,10 +126,10 @@ module Jekyll def links @links ||= begin - if page["seo"] && page["seo"]["links"] - page["seo"]["links"] - elsif homepage_or_about? && site["social"] && site["social"]["links"] - site["social"]["links"] + if page_seo["links"] + page_seo["links"] + elsif homepage_or_about? && site_social["links"] + site_social["links"] end end end @@ -243,7 +243,29 @@ module Jekyll end def seo_name - @seo_name ||= format_string(page["seo"]["name"]) if page["seo"] + @seo_name ||= format_string(page_seo["name"]) if page_seo["name"] + end + + def page_seo + @page_seo ||= sub_hash(page, "seo") + end + + def site_social + @site_social ||= sub_hash(site, "social") + end + + # Safely returns a sub hash + # + # hash - the parent hash + # key - the key in the parent hash + # + # Returns the sub hash or an empty hash, if it does not exist + def sub_hash(hash, key) + if hash[key].is_a?(Hash) + hash[key] + else + {} + end end end end diff --git a/spec/jekyll_seo_tag/drop_spec.rb b/spec/jekyll_seo_tag/drop_spec.rb index 0530c88..cf6c5da 100644 --- a/spec/jekyll_seo_tag/drop_spec.rb +++ b/spec/jekyll_seo_tag/drop_spec.rb @@ -122,6 +122,14 @@ RSpec.describe Jekyll::SeoTag::Drop do end end + context "with site.social as an array" do + let(:config) { { "social" => %w(a b) } } + + it "uses site.social.name" do + expect(subject.name).to be_nil + end + end + it "uses the site title" do expect(subject.name).to eql("site title") end @@ -317,6 +325,14 @@ RSpec.describe Jekyll::SeoTag::Drop do end end + context "with seo as an array" do + let(:page_meta) { { "seo" => %w(a b) } } + + it "uses seo.type" do + expect(subject.type).to eql("WebPage") + end + end + context "the homepage" do let(:page_meta) { { "permalink" => "/" } }