Skip to content

Instantly share code, notes, and snippets.

@fabioyamate
Created November 23, 2011 12:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fabioyamate/1388568 to your computer and use it in GitHub Desktop.
Save fabioyamate/1388568 to your computer and use it in GitHub Desktop.
Paperclip - remove attachment
class Model < ActiveRecord::Base
has_attached_file :icon
has_removable_file :icon
end
module Paperclip
module RemovableAttachment
def self.included(base)
base.extend(ClassMethods)
base.send(:include, InstanceMethods)
end
module ClassMethods
attr_reader :removable_attachments
def has_removable_file(*attrs)
attrs.each do |name|
class_eval <<-METHOD, __FILE__, __LINE__
attr_accessor :delete_#{name}
def delete_#{name}=(value)
@delete_#{name} = !value.to_i.zero?
end
def delete_#{name}
!!@delete_#{name}
end
alias_method :delete_#{name}?, :delete_#{name}
METHOD
end
@removable_attachments = attrs
before_validation :clear_removable_attachment
end
end
module InstanceMethods
private
def clear_removable_attachment
self.class.removable_attachments.each do |name|
self.send("#{name}=", nil) if self.send("delete_#{name}?") && !self.send(name).dirty?
end
end
end
end
end
require 'spec_helper'
require 'active_record'
ActiveRecord::Schema.define do
create_table "user_examples", :force => true do |t|
t.string :avatar_file_name
end
end
class Attachment
attr_accessor :dirty
def dirty?; @dirty; end
end
class UserExample < ActiveRecord::Base
include Paperclip::RemovableAttachment
attr_accessor :avatar
has_removable_file :avatar
end
describe "Paperclip::RemovableAttachment" do
before(:each) do
a = Attachment.new
a.dirty = true
@u = UserExample.new(:avatar_file_name => 'avatar.png', :avatar => a)
end
it 'should respond to delete virtual attributes for each removable attachment' do
@u.should respond_to('delete_avatar=')
@u.should respond_to('delete_avatar')
@u.should respond_to('delete_avatar?')
end
it 'should have removable attribute on list of removable attachments' do
@u.class.removable_attachments.should include(:avatar)
end
it 'should remove attachment if delete attribute is 1 if attachment is new' do
@u.avatar.dirty = false
@u.avatar.should_not be_nil
@u.update_attributes(:delete_avatar => "1")
@u.avatar.should be_nil
end
it 'should not remove attachment with delete attribute setted to 1 if uploaded file changed' do
@u.avatar.dirty = true
@u.avatar.should_not be_nil
@u.update_attributes(:delete_avatar => "1")
@u.avatar.should_not be_nil
end
it 'should not remove attachment if delete attribute is 0' do
@u.avatar.dirty = true
@u.avatar.should_not be_nil
@u.update_attributes(:delete_avatar => "0")
@u.avatar.should_not be_nil
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment