Attachment Fu Validates As Attachment Hack

November 28, 2007

Recent err the blog posted about the my evil twin hack technique

In this post they detail how to hack plugins nicely and provide an example on how to hack attachment_fu. It turns out that I have been spending quite a bit of time with attachment_fu on various projects recently and have started to need it to do slightly different things.

Below is a hack I have written to improve validates_as_attachment. Using the evil twin technique this will just ask for a file to be uploaded if you dont upload anything. Instead of spewing out a whole load of errors that dont help the user much.

klass = Technoweenie::AttachmentFu::ClassMethods
klass.module_eval do

def validates_as_attachment
validate :uploaded_data_is_present
validates_presence_of :size, :content_type, :filename, :if => :uploaded_data?
validate              :attachment_attributes_valid?
end

end

klazz = Technoweenie::AttachmentFu::InstanceMethods
klazz.module_eval do
def uploaded_data?
  return false unless filename
  true
end

# validates the size and content_type attributes according to the current model's options
def attachment_attributes_valid?
if uploaded_data?
[:size, :content_type].each do |attr_name|
enum = attachment_options[attr_name]
errors.add attr_name, ActiveRecord::Errors.default_error_messages[:inclusion] unless enum.nil? || enum.include?(send(attr_name))
end
end
end

def uploaded_data_is_present
unless uploaded_data?
errors.add_to_base("You must select a file to upload.")
end
end

end

This serves as a drop in replacement for validates_as_attachment