require 'peoplefinder/image_uploader'
require 'peoplefinder/person'
class DetoxifyYaml < ActiveRecord::Migration
  class Version < ActiveRecord::Base
  end

  def up
    Version.all.each do |version|
      serialized = version.object_changes
      serialized.gsub!(/ !ruby\/object:Peoplefinder::ImageUploader::Uploader\d+/, '')
      changes = YAML.load(serialized)
      if changes.key?('image')
        changes['image'].map! do |value|
          value.url && File.basename(value.url)
        end
      end
      version.update! object_changes: YAML.dump(changes)
    end
  end
end

require 'peoplefinder/image_uploader'
require 'peoplefinder/person'
class DetoxifyYaml < ActiveRecord::Migration
  class Version < ActiveRecord::Base
  end

  def clean_yaml(yaml)
    yaml.gsub(/ !ruby\/object:Peoplefinder::ImageUploader::Uploader\d+/, '')
  end

  def extract_url(image)
    if image.respond_to?(:url)
      image.url && File.basename(image.url)
    else
      image
    end
  end

  def clean_object_changes(version)
    serialized = version.object_changes
    return if serialized.blank?

    hash = YAML.load(clean_yaml(serialized))
    if hash.key?('image')
      hash['image'].map! { |img| extract_url(img) }
      version.update! object_changes: YAML.dump(hash)
    end
  end

  def clean_object(version)
    serialized = version.object
    return if serialized.blank?

    hash = YAML.load(clean_yaml(serialized))
    if hash.key?('image')
      hash['image'] = extract_url(hash['image'])
      version.update! object: YAML.dump(hash)
    end
  end

  def up
    Version.all.each do |version|
      clean_object_changes version
      clean_object version
    end
  end
end

Make the version YAML fix more robust
Make the version YAML fix more robust

* Don't try to correct new versions created after the code changed, i.e.
  where the image is already a string
* Fix the 'object' field as well, which also contained broken YAML.
* Don't try to fix blank YAML: if the event is destroy, then object_changes
  is nil.
