Skip to content

Commit

Permalink
Export the image element href attribute as a link (#139)
Browse files Browse the repository at this point in the history
If the image element has an href attribute, we nest the figure tag of the image
inside a link.
  • Loading branch information
towanda authored and nicolas-fricke committed Nov 5, 2018
1 parent 61f6fcc commit ac7bcf5
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 5 deletions.
22 changes: 18 additions & 4 deletions lib/article_json/export/common/html/elements/image.rb
Original file line number Diff line number Diff line change
Expand Up @@ -7,24 +7,38 @@ module Image
include ArticleJSON::Export::Common::HTML::Elements::Shared::Caption
include ArticleJSON::Export::Common::HTML::Elements::Shared::Float

# Generate the `<figure>` node containing the image and caption
# Generate the `<figure>` node containing the image and caption or
# an `<a>` node containing the `<figure>` 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?
Expand Down
32 changes: 31 additions & 1 deletion spec/article_json/export/html/elements/image_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -45,5 +47,33 @@
let(:expected_html) { '<figure><img src="/foo/bar.jpg"></figure>' }
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
'<figure><a href="http://devex.com">' \
'<img src="/foo/bar.jpg"></a></figure>'
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
'<figure><a href="http://devex.com">' \
'<img src="/foo/bar.jpg"></a>' \
'<figcaption><a href="http://foo.io">Foo Bar</a></figcaption></figure>'
end
it { should eq expected_html }
end
end
end

0 comments on commit ac7bcf5

Please sign in to comment.