diff --git a/app/repositories/story_repository.rb b/app/repositories/story_repository.rb index d94e4edc2..7c027d211 100644 --- a/app/repositories/story_repository.rb +++ b/app/repositories/story_repository.rb @@ -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 @@ -45,6 +47,21 @@ 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"), @@ -52,4 +69,4 @@ def self.samples SampleStory.new("Lambda Da Ultimate", "Flimsy types are the new hotness") ] end -end \ No newline at end of file +end diff --git a/spec/repositories/story_repository_spec.rb b/spec/repositories/story_repository_spec.rb new file mode 100644 index 000000000..ddfe82123 --- /dev/null +++ b/spec/repositories/story_repository_spec.rb @@ -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 = 'bar' + expect(klass.urls_to_absolute(content, nil)).to eq(content) + end + + it "replaces relative urls in a, img and video tags" do + content = <<-EOS +
+ +tee + +
+ EOS + expect(klass.urls_to_absolute(content, "http://oodl.io/d/").gsub(/\n/, "")) + .to eq((<<-EOS).gsub(/\n/, "")) +
+ +tee + + +
+ EOS + end + end +end