Last active
November 9, 2016 05:45
Star
You must be signed in to star a gist
Paperclip で保存する画像の寸法チェックをする ref: http://qiita.com/shimx/items/ff69afa83075d6ef61cf
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
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 |
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
{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 |
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
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