Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 20 additions & 3 deletions app/repositories/story_repository.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,12 @@

class StoryRepository
def self.add(entry, feed)
url = entry.url
content = extract_content(entry)
Story.create(feed: feed,
title: entry.title,
permalink: entry.url,
body: StoryRepository.extract_content(entry),
permalink: url,
body: urls_to_absolute(content, url),
is_read: false,
published: entry.published || Time.now)
end
Expand Down Expand Up @@ -45,11 +47,26 @@ def self.extract_content(entry)
end
end

def self.urls_to_absolute(content, base_url)
doc = Nokogiri::HTML.fragment(content)
abs_re = URI::DEFAULT_PARSER.regexp[:ABS_URI]
[["a", "href"], ["img", "src"], ["video", "src"]].each do |tag, attr|
doc.css(tag).each do |node|
url = node.get_attribute(attr)
unless url =~ abs_re
node.set_attribute(attr, URI.join(base_url, url).to_s)
URI.parse(url)
end
end
end
doc.to_html
end

def self.samples
[
SampleStory.new("Darin' Fireballs", "Why you should trade your firstborn for a Retina iPad"),
SampleStory.new("TechKrunch", "SugarGlidr raises $1.2M Series A for Social Network for Photo Filters"),
SampleStory.new("Lambda Da Ultimate", "Flimsy types are the new hotness")
]
end
end
end
32 changes: 32 additions & 0 deletions spec/repositories/story_repository_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
require "spec_helper"
app_require "repositories/story_repository"

describe StoryRepository do
klass = described_class

describe ".urls_to_absolute" do
it "preserves existing absolute urls" do
content = '<a href="http://foo">bar</a>'
expect(klass.urls_to_absolute(content, nil)).to eq(content)
end

it "replaces relative urls in a, img and video tags" do
content = <<-EOS
<div>
<img src="https://foo">
<a href="/bar/baz">tee</a><img src="bar/bar">
<video src="/tee"></video>
</div>
EOS
expect(klass.urls_to_absolute(content, "http://oodl.io/d/").gsub(/\n/, ""))
.to eq((<<-EOS).gsub(/\n/, ""))
<div>
<img src="https://foo">
<a href="http://oodl.io/bar/baz">tee</a>
<img src="http://oodl.io/d/bar/bar">
<video src="http://oodl.io/tee"></video>
</div>
EOS
end
end
end