Created
March 7, 2014 09:17
Checking and Limiting File Size of Uploaded Files with Carrierwave
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
# NOTE: There must be a better way to do this - help appreciated! | |
############################################################### | |
# uploaded_file.rb - utility class | |
############################################################### | |
class UploadedFile | |
def self.size(file) | |
uploaded?(file) ? file.size : nil | |
end | |
# NOTE: if I attempt to check the file size without making sure there is a file upload the fog rubygem bombs. | |
def self.size_limit_exceeded?(file, file_size_limit) | |
puts "UploadedFile.size_limit_exceeded? original_filename=#{original_filename(file)} uploaded=#{uploaded?(file)} file_class=#{file.class.name} file_size_limit=#{file_size_limit} file_size=#{size(file)}" | |
uploaded?(file) && size(file) > file_size_limit.megabytes | |
end | |
# FIXME: There must be a cleaner way to check if a file has been uploaded with Carrierwave | |
# NOTE: When the file is uploaded it seems to be an instance of CarrierWave::SanitizedFile and when | |
# it is not uploaded it's an instance of CarrierWave::Storage::Fog::File | |
def self.uploaded?(file) | |
original_filename(file).present? | |
end | |
def self.original_filename(file) | |
if file && file.respond_to?(:original_filename) | |
file.original_filename | |
else | |
nil | |
end | |
end | |
end | |
############################################################### | |
# limit_file_size_validator.rb - rails validator | |
############################################################### | |
class LimitFileSizeValidator < ActiveModel::EachValidator | |
def validate_each(record, attribute, value) | |
if UploadedFile.size_limit_exceeded?(record.send(attribute).file, file_size_limit) | |
record.errors[attribute] << "must not be larger than #{file_size_limit} MB" | |
end | |
end | |
private | |
def file_size_limit | |
options[:max] || Rails.application.config.file_size_limit | |
end | |
end | |
############################################################### | |
# Usage in Rails ActiveRecord model | |
############################################################### | |
mount_uploader :pdf, PdfUploader | |
validates :pdf, limit_file_size: true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment