1
0
Fork 0
This repository has been archived on 2023-03-27. You can view files and clone it, but cannot push or open issues or pull requests.
lpr-partynest/app/validators/image_validator.rb

60 lines
1.1 KiB
Ruby
Raw Normal View History

2019-03-24 23:04:53 -04:00
# frozen_string_literal: true
class ImageValidator < ApplicationEachValidator
class Validation < Validation
MAX_SIZE = 1.megabyte
CONTENT_TYPES = %w[
image/png
image/jpeg
image/gif
].freeze
2019-03-25 10:15:37 -04:00
EXTENSIONS = %w[
png
jpg
jpeg
gif
].freeze
2019-03-24 23:04:53 -04:00
def perform
return unless value.attached?
2019-03-25 10:07:58 -04:00
case value
when ActiveStorage::Attached::One
check value
when ActiveStorage::Attached::Many
value.attachments.each(&method(:check))
else
raise TypeError
2019-03-24 23:04:53 -04:00
end
2019-03-25 10:07:58 -04:00
end
def check(item)
2019-03-25 10:26:33 -04:00
check_format item
check_ext item
check_size item
end
2019-03-25 10:07:58 -04:00
2019-03-25 10:26:33 -04:00
def check_format(item)
return if item.blob.content_type.in? CONTENT_TYPES
error :image_format, content_type: item.blob.content_type
end
def check_ext(item)
return if item.blob.filename.extension.in? EXTENSIONS
error :image_ext, ext: item.blob.filename.extension
end
2019-03-25 10:15:37 -04:00
2019-03-25 10:26:33 -04:00
def check_size(item)
2019-03-25 10:07:58 -04:00
error :image_size unless item.blob.byte_size <= max_size
end
2019-03-24 23:04:53 -04:00
2019-03-25 10:07:58 -04:00
def max_size
MAX_SIZE
2019-03-24 23:04:53 -04:00
end
end
end