From 0b8b6900ac0a021271b4da6b036ddbbc6e125ea6 Mon Sep 17 00:00:00 2001 From: Victor Costa Date: Thu, 13 Mar 2014 16:28:59 -0300 Subject: [PATCH] Set relative path to images and link on TextArticle --- app/models/text_article.rb | 19 +++++++++++++++++++ test/unit/text_article_test.rb | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 66 insertions(+), 0 deletions(-) diff --git a/app/models/text_article.rb b/app/models/text_article.rb index 8c41e04..82c07d4 100644 --- a/app/models/text_article.rb +++ b/app/models/text_article.rb @@ -20,4 +20,23 @@ class TextArticle < Article def can_display_versions? true end + + before_save :set_relative_path + + def set_relative_path + parsed = Hpricot(self.body.to_s) + parsed.search('img[@src]').map { |i| change_element_path(i, 'src') } + parsed.search('a[@href]').map { |i| change_element_path(i, 'href') } + self.body = parsed.to_s + end + + def change_element_path(el, attribute) + fullpath = /(https?):\/\/(#{environment.default_hostname})(:\d+)?(\/.*)/.match(el[attribute]) + if fullpath + domain = fullpath[2] + path = fullpath[4] + el[attribute] = path if domain == environment.default_hostname + end + end + end diff --git a/test/unit/text_article_test.rb b/test/unit/text_article_test.rb index dbc73c0..eb9b7e5 100644 --- a/test/unit/text_article_test.rb +++ b/test/unit/text_article_test.rb @@ -37,4 +37,51 @@ class TextArticleTest < ActiveSupport::TestCase assert_equal Blog.icon_name, TextArticle.icon_name(article) end + should 'change image path to relative' do + person = create_user('testuser').person + article = TextArticle.new(:profile => person, :name => 'test') + env = Environment.default + article.body = "" + article.save! + assert_equal "", article.body + end + + should 'change link to relative path' do + person = create_user('testuser').person + article = TextArticle.new(:profile => person, :name => 'test') + env = Environment.default + article.body = "test" + article.save! + assert_equal "test", article.body + end + + should 'change image path to relative for domain with https' do + person = create_user('testuser').person + article = TextArticle.new(:profile => person, :name => 'test') + env = Environment.default + article.body = "" + article.save! + assert_equal "", article.body + end + + should 'change image path to relative for domain with port' do + person = create_user('testuser').person + article = TextArticle.new(:profile => person, :name => 'test') + env = Environment.default + article.body = "" + article.save! + assert_equal "", article.body + end + + should 'change image path to relative for domain with www' do + person = create_user('testuser').person + article = TextArticle.new(:profile => person, :name => 'test') + env = Environment.default + env.force_www = true + env.save! + article.body = "" + article.save! + assert_equal "", article.body + end + end -- libgit2 0.21.2