Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save calavera/55946 to your computer and use it in GitHub Desktop.
Save calavera/55946 to your computer and use it in GitHub Desktop.
require 'paperclip/geometry'
module Paperclip
module ClassMethods
# Places ActiveRecord-style validations on the width of the file assigned. The
# possible options are:
# * +in+: a Range of pixels (i.e. +10..100+),
# * +less_than+: equivalent to :in => 0..options[:less_than]
# * +greater_than+: equivalent to :in => options[:greater_than]..Infinity
# * +message+: error message to display, use :min and :max as replacements
def validates_attachment_width name, options = {}
validates_attachament_aspect(:width, name, options)
end
# Places ActiveRecord-style validations on the height of the file assigned. The
# possible options are:
# * +in+: a Range of pixels (i.e. +1..1.megabyte+),
# * +less_than+: equivalent to :in => 0..options[:less_than]
# * +greater_than+: equivalent to :in => options[:greater_than]..Infinity
# * +message+: error message to display, use :min and :max as replacements
def validates_attachment_height name, options = {}
validates_attachament_aspect(:height, name, options)
end
def validates_attachement_aspect(aspect, name, options = {})
min = options[:greater_than] || (options[:in] && options[:in].first) || 0
max = options[:less_than] || (options[:in] && options[:in].last) || (1.0/0)
range = (min..max)
message = options[:message] || "file #{aspect.to_s} must be between :min and :max pixels."
attachment_definitions[name][:validations][aspect] = lambda do |attachment, instance|
if attachment.file? && !range.include?( Geometry.from_file(attachment.queued_for_write[:original]).send(aspect).to_i )
message.gsub(/:min/, min.to_s).gsub(/:max/, max.to_s)
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment