Add a validation method to check file extension

120 views
Skip to first unread message

macarthy

unread,
Oct 2, 2008, 2:37:23 PM10/2/08
to Paperclip Plugin
What is the best way to add this functionality ?

validates_attachment_extension_type :myfile, :extensions =>
GOOD_EXTENSIONS

I tried replicating the process of the
validates_attachment_content_type but for some reason couldn't get it
to work , here is what I tried:

in paperclip.rb

def validates_attachment_extension_type name, options = {}
attachment_definitions[name][:validations] << lambda do |
attachment, instance|
valid_types = [options[:extensions]].flatten

unless attachment.original_filename.nil?
unless options[:extensions].blank?
ext = instance[:"#{name}_xtension"]
unless valid_types.any?{|t| t === ext }
options[:message] || "is not one of the allowed file
types.(was #{ext})"
end
end
end
end

In attachment.rb

@instance[:"#{@name}_file_size"] = uploaded_file.size.to_i
@instance[:"#{@name}_updated_at"] = Time.now
@instance[:"#{@name}_xtension"] =
(uploaded_file.original_filename.match(/\.(\w+)$/)[1] rescue "octet-
stream").downcase
@dirty = true


def queue_existing_for_delete #:nodoc:
return unless file?
logger.info("[paperclip] Queueing the existing files for #{name}
for deletion.")
@queued_for_delete += [:original, *@styles.keys].uniq.map do |
style|
path(style) if exists?(style)
end.compact
@instance[:"#{@name}_file_name"] = nil
@instance[:"#{@name}_content_type"] = nil
@instance[:"#{@name}_file_size"] = nil
@instance[:"#{@name}_updated_at"] = nil
@instance[:"#{@name}_xtension"] = nil
end

end


Thanks

Jonathan Yurek

unread,
Oct 24, 2008, 4:22:02 PM10/24/08
to papercli...@googlegroups.com
That looks like a correct validation method. Why are you using an
"xtension" column instead of using File.extname(orginal_filename),
though? What is going wrong with your validation? Is it not running,
or is it not running correctly?

--
Jonathan Yurek, Founder and CTO
thoughtbot, inc.
organic brains. digital solutions.

617.482.1300 x114
http://www.thoughtbot.com/

Reply all
Reply to author
Forward
0 new messages