Skip to content

Instantly share code, notes, and snippets.

@kyleslattery
Forked from ashrewdmint/validators.rb
Created July 22, 2009 04:29
Show Gist options
  • Save kyleslattery/151811 to your computer and use it in GitHub Desktop.
Save kyleslattery/151811 to your computer and use it in GitHub Desktop.
# 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, :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.is_a?(Tempfile)
record.errors.add(attr_name, 'must be a file')
next
end
unless value.original_filename =~ Regexp.new('\.(' + options[:extensions].join('|') + ')$')
record.errors.add(attr_name, 'must have one of the following extensions: ' + options[:extensions].join(', '))
end
if value.size > options[:max_size].megabytes
readable_size = options[:max_size].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