From 1d52e065325430eb8a371e6e43c024e5989e2ddf Mon Sep 17 00:00:00 2001 From: danielvincent Date: Fri, 17 Dec 2010 20:22:49 -0800 Subject: [PATCH] added rake task and spec for absolutifying existing image links --- lib/tasks/migrations.rake | 24 +++++++++++++++ spec/lib/tasks/migrations_spec.rb | 50 +++++++++++++++++++++++++++++++ 2 files changed, 74 insertions(+) create mode 100644 spec/lib/tasks/migrations_spec.rb diff --git a/lib/tasks/migrations.rake b/lib/tasks/migrations.rake index 400217331..9c46d830c 100644 --- a/lib/tasks/migrations.rake +++ b/lib/tasks/migrations.rake @@ -33,4 +33,28 @@ namespace :migrations do desc 'execute mongo to mysql migration. Requires mongoexport to be accessible.' task :migrate_to_mysql => [:export_for_mysql, :import_to_mysql] + + desc 'absolutify all existing image references' + task :absolutify_image_references do + require File.join(Rails.root,"config/environment") + + Photo.all.each do |photo| + # extract root + unless photo.image.url.match(/^https?:\/\//) + + pod_url = photo.person.url + pod_url.chop! if pod_url[-1,1] == '/' + remote_path = "#{pod_url}#{photo.image.url}" + else + remote_path = photo.image.url + end + + # get path/filename + name_start = remote_path.rindex '/' + photo.remote_photo_path = "#{remote_path.slice(0, name_start)}/" + photo.remote_photo_name = remote_path.slice(name_start + 1, remote_path.length) + + photo.save! + end + end end diff --git a/spec/lib/tasks/migrations_spec.rb b/spec/lib/tasks/migrations_spec.rb new file mode 100644 index 000000000..eb7c9abcc --- /dev/null +++ b/spec/lib/tasks/migrations_spec.rb @@ -0,0 +1,50 @@ +# Copyright (c) 2010, Diaspora Inc. This file is +# licensed under the Affero General Public License version 3 or later. See +# the COPYRIGHT file. + +require 'spec_helper' +require File.join(Rails.root, 'lib/hcard') +require "rake" + +describe 'migrations' do + + describe 'absolutify_image_references' do + before do + @rake = Rake::Application.new + Rake.application = @rake + Rake.application.rake_require "lib/tasks/migrations", [Rails.root] + Rake::Task.define_task(:environment) {} + + @fixture_filename = 'button.png' + @fixture_name = File.join(File.dirname(__FILE__), '..', '..', 'fixtures', @fixture_filename) + + @photos = [] + + 5.times do |n| + photo = Photo.instantiate(:user_file => File.open(@fixture_name)) + photo.remote_photo_path = nil + photo.remote_photo_name = nil + + photo.person = (n % 2 == 0 ? make_user.person : Factory(:person, :url => "https://remote.com/")) + @photos[n] = photo + @photos[n].save + end + end + + it 'sets remote_photo_path and remote_photo_name' do + @rake['migrations:absolutify_image_references'].invoke + + @photos.each do |photo| + photo.reload + + photo.remote_photo_path.should be_true + photo.remote_photo_name.should be_true + photo.url.match(/$http.*jpg^/) + end + + @photos[0].remote_photo_path.should include("http://google-") + @photos[1].remote_photo_path.should include("https://remote.com/") + end + end +end +