[rails]carrierwaveに画像サイズ制限を追加する


Ruby2.1, Rails4.1.1で確認

carrierwaveを使って画像アップロードをする際に、画像サイズの制限をかけたい場合のメモ

  • まずは こちらのGistからfile_size_validator.rbをダウンロードし、lib/validators以下に設置
# lib/validators/file_size_validator.rb
# Based on: https://gist.github.com/795665

class FileSizeValidator < ActiveModel::EachValidator
  MESSAGES  = { :is => :wrong_size, :minimum => :size_too_small, :maximum => :size_too_big }.freeze
  CHECKS    = { :is => :==, :minimum => :>=, :maximum => :<= }.freeze

  DEFAULT_TOKENIZER = lambda { |value| value.split(//) }
  RESERVED_OPTIONS  = [:minimum, :maximum, :within, :is, :tokenizer, :too_short, :too_long]

  def initialize(options)
    if range = (options.delete(:in) || options.delete(:within))
      raise ArgumentError, ":in and :within must be a Range" unless range.is_a?(Range)
      options[:minimum], options[:maximum] = range.begin, range.end
      options[:maximum] -= 1 if range.exclude_end?
    end

    super
  end

  def check_validity!
    keys = CHECKS.keys & options.keys

    if keys.empty?
      raise ArgumentError, 'Range unspecified. Specify the :within, :maximum, :minimum, or :is option.'
    end

    keys.each do |key|
      value = options[key]

      unless value.is_a?(Integer) && value >= 0
        raise ArgumentError, ":#{key} must be a nonnegative Integer"
      end
    end
  end

  def validate_each(record, attribute, value)
    raise(ArgumentError, "A CarrierWave::Uploader::Base object was expected") unless value.kind_of? CarrierWave::Uploader::Base

    value = (options[:tokenizer] || DEFAULT_TOKENIZER).call(value) if value.kind_of?(String)

    CHECKS.each do |key, validity_check|
      next unless check_value = options[key]

      value ||= [] if key == :maximum

      value_size = value.size
      next if value_size.send(validity_check, check_value)

      errors_options = options.except(*RESERVED_OPTIONS)
      errors_options[:file_size] = help.number_to_human_size check_value

      default_message = options[MESSAGES[key]]
      errors_options[:message] ||= default_message if default_message

      record.errors.add(attribute, MESSAGES[key], errors_options)
    end
  end

  def help
    Helper.instance
  end

  class Helper
    include Singleton
    include ActionView::Helpers::NumberHelper
  end
end
  • lib以下をautoloadするようにapplication.rbを修正
#config/application.rb

  class Application < Rails::Application
    config.autoload_paths += %W(#{config.root}/lib)
    config.autoload_paths += Dir["#{config.root}/lib/**/"]
  end
  • エラーメッセージをlocaleに設定
# config/locales/models/default/ja.yml
ja:
  errors:
    messages:
      wrong_size: "のサイズは%{file_size}に設定してください"
      size_too_small: "のサイズは小さすぎます(%{file_size}以上に設定してください)"
      size_too_big: "のサイズは大きすぎます(%{file_size}以下に設定してください)"

# config/locales/models/default/en.yml
en:
  errors:
    messages:
      wrong_size: "is the wrong size (should be %{file_size})"
      size_too_small: "is too small (should be at least %{file_size})"
      size_too_big: "is too big (should be at most %{file_size})"
  • modelのvalidatesに画像サイズ制限を追加
  mount_uploader :image, ImageUploader

  validates :image,
    presence: true, on: :create, # create時のみ必須
    file_size: {
      maximum: 10.megabytes.to_i # 最大10MBに制限
    }

これで画像サイズ制限ができました

参考