module HasAttachedFileExtensions

Public Instance Methods

define() click to toggle source
Calls superclass method
# File lib/paperclip/staging.rb, line 37
def define
  super
  define_accessor_staging
end
define_accessor_staging() click to toggle source
# File lib/paperclip/staging.rb, line 42
def define_accessor_staging
  name = @name
  staging_getter_name = "#{name.to_s}_staging".to_sym
  staging_setter_name = "#{name.to_s}_staging=".to_sym

  already_updated_ivar = "@attachment_#{name}_already_updated".to_sym

  @klass.send :define_method, staging_getter_name do
    ivar = "@attachment_#{name}"
    attachment = instance_variable_get(ivar)
    return nil unless attachment
    queued = attachment.queued_for_write[:original]
    if queued
      filename = attachment.original_filename
      type = attachment.content_type
      body = File.read(queued.path)
      [filename, type, body].map{|text|Base64.strict_encode64(text)}.join('|')
    end
  end

  old_attachment_setter = "#{name.to_s}_original_setter".to_sym
  @klass.send :alias_method, old_attachment_setter, "#{@name}="

  @klass.send :define_method, "#{@name}=" do |file|
    instance_variable_set(already_updated_ivar, true)
    send(old_attachment_setter, file)
  end

  @klass.send :define_method, staging_setter_name do |value|
    return if value.blank?
    already_updated = instance_variable_get(already_updated_ivar)
    return if already_updated
    filename, type, body = value.split('|').map{|text|Base64.strict_decode64(text)}
    send(name).assign(NamedStringIO.new(body, filename, type))
  end
end