From ac7bcf573786bd03e750a7b59bb67a71dee9d003 Mon Sep 17 00:00:00 2001 From: Manu Campos Date: Mon, 5 Nov 2018 18:12:31 +0100 Subject: [PATCH] Export the image element href attribute as a link (#139) If the image element has an href attribute, we nest the figure tag of the image inside a link. --- .../export/common/html/elements/image.rb | 22 ++++++++++--- .../export/html/elements/image_spec.rb | 32 ++++++++++++++++++- 2 files changed, 49 insertions(+), 5 deletions(-) diff --git a/lib/article_json/export/common/html/elements/image.rb b/lib/article_json/export/common/html/elements/image.rb index e13056b..8524f35 100644 --- a/lib/article_json/export/common/html/elements/image.rb +++ b/lib/article_json/export/common/html/elements/image.rb @@ -7,24 +7,38 @@ module Image include ArticleJSON::Export::Common::HTML::Elements::Shared::Caption include ArticleJSON::Export::Common::HTML::Elements::Shared::Float - # Generate the `
` node containing the image and caption + # Generate the `
` node containing the image and caption or + # an `` node containing the `
` node if href is present. # @return [Nokogiri::XML::Element] def export + figure_node + end + + private + + # @return [Nokogiri::XML::NodeSet] + def figure_node create_element(:figure, node_opts) do |figure| - figure.add_child(image_node) + node = @element.href.present? ? href_node : image_node + figure.add_child(node) if @element.caption&.any? figure.add_child(caption_node(:figcaption)) end end end - private - # @return [Nokogiri::XML::NodeSet] def image_node create_element(:img, src: @element.source_url) end + # @return [Nokogiri::XML::NodeSet] + def href_node + create_element(:a, href: @element.href) do |a| + a.add_child(image_node) + end + end + # @return [Hash] def node_opts return if floating_class.nil? diff --git a/spec/article_json/export/html/elements/image_spec.rb b/spec/article_json/export/html/elements/image_spec.rb index efc777a..c666541 100644 --- a/spec/article_json/export/html/elements/image_spec.rb +++ b/spec/article_json/export/html/elements/image_spec.rb @@ -5,10 +5,12 @@ ArticleJSON::Elements::Image.new( source_url: '/foo/bar.jpg', caption: caption, - float: float + float: float, + href: url ) end let(:float) { nil } + let(:url) { nil } let(:caption) { [ArticleJSON::Elements::Text.new(content: 'Foo Bar')] } describe '#export' do @@ -45,5 +47,33 @@ let(:expected_html) { '
' } it { should eq expected_html } end + + context 'when the image has an href' do + let(:caption) { [] } + let(:url) { 'http://devex.com' } + let(:expected_html) do + '
' \ + '
' + end + it { should eq expected_html } + end + + context 'when the image has an href and a caption with a link' do + let(:caption) do + [ + ArticleJSON::Elements::Text.new( + content: 'Foo Bar', + href: 'http://foo.io' + ) + ] + end + let(:url) { 'http://devex.com' } + let(:expected_html) do + '
' \ + '' \ + '
Foo Bar
' + end + it { should eq expected_html } + end end end