Skip to content

Instantly share code, notes, and snippets.

@ashrewdmint
Created July 22, 2009 03:46
Show Gist options
  • Save ashrewdmint/151779 to your computer and use it in GitHub Desktop.
Save ashrewdmint/151779 to your computer and use it in GitHub Desktop.
validates_as_file validator
# Helpful stuff from: http://chrisblunt.com/blog/2009/04/18/rails-writing-dry-custom-validators/
ActiveRecord::Base.class_eval do
def self.validates_as_file(*attr_names)
options = {:max_size => 1 * 1024**2, :extensions => '.txt'}.merge(attr_names.extract_options!)
options[:extensions] = [options[:extensions]] unless options[:extensions].is_a?(Array)
validates_each(attr_names, options) do |record, attr_name, value|
unless value.class == Tempfile
record.errors.add(attr_name, 'must be a file') unless value.class == Tempfile
end
unless value.class != Tempfile or value.original_filename =~ Regexp.new('\.(' + options[:extensions].join('|') + ')$')
record.errors.add(attr_name, 'must have one of the following extensions: ' + options[:extensions].join(', '))
end
unless value.class != Tempfile or value.size < options[:max_size]
readable_size = ((10 / 1024.0**2 * 10).ceil / 10.0).to_s + ' Mb'
record.errors.add(attr_name, 'must not be greater than ' + readable_size)
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment