Skip to content

Instantly share code, notes, and snippets.

@shimx
Last active November 9, 2016 05:45
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save shimx/e4097ac8443541eadf6d24a3e9f7eb78 to your computer and use it in GitHub Desktop.
Paperclip で保存する画像の寸法チェックをする ref: http://qiita.com/shimx/items/ff69afa83075d6ef61cf
class ImageDimensionsValidator < ActiveModel::EachValidator
CHECKS = { greater_than: :>, greater_than_or_equal_to: :>=,
equal_to: :==, less_than: :<, less_than_or_equal_to: :<= }.freeze
SIDES = [:width, :height].freeze
def validate_each(record, attribute, value)
dimensions = Paperclip::Geometry.from_file(value.queued_for_write[:original].path)
SIDES.each do |side|
next if options[side].blank?
CHECKS.keys.each do |check|
next if options[side][check].blank? || dimensions.send(side).send(CHECKS[check], options[side][check])
record.errors[attribute] << "#{side} (#{dimensions.send(side)}px) must be #{check} #{options[side][check]}px"
end
end
end
def check_validity!
SIDES.each do |side|
next if options[side].blank?
unless CHECKS.keys.any? { |argument| options[side][argument].present? }
fail ArgumentError, "You must pass either :#{CHECKS.keys.join(', :')} to the validator"
end
end
end
end
{less_than: INT} # INTより小さい長さの画像ならOK
{less_than_or_equal_to: INT} # INT以下の長さの画像ならOK
{greater_than: INT} # INTより大きい長さの画像ならOK
{greater_than_or_equal_to: INT} # INT以上の長さの画像ならOK
{equal_to: INT} # INTと同じ長さの画像ならOK
class SampleImage < ActiveRecord::Base
has_attached_file :file, IMAGE_OPTIONS
# widthが640px以上、かつheightが460px以上の画像ならOK
validates :file, image_dimensions: {
width: {greater_than_or_equal_to: 640},
height: {greater_than_or_equal_to: 460}
}, if: -> {file.dirty?} # upload時のみ寸法のvalidate
....
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment