-
-
Save kyleslattery/151811 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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