Module: Bulldog::Validations::ClassMethods

Defined in:
lib/bulldog/validations.rb

Instance Method Summary collapse

Instance Method Details

#validates_attachment_file_size_of(name, options = {}) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/bulldog/validations.rb', line 15

def validates_attachment_file_size_of(name, options={})
  if (range = options.delete(:in))
    options[:greater_than] = range.min - 1
    options[:less_than   ] = range.max + 1
  end
  validates_each(name, options) do |record, attribute, attachment|
    if attachment.present?
      file_size = attachment.file_size
      if options[:greater_than]
        file_size > options[:greater_than] or
          record.errors.add attribute, options[:message] || :attachment_too_small
      end
      if options[:less_than]
        file_size < options[:less_than] or
          record.errors.add attribute, options[:message] || :attachment_too_large
      end
    end
  end
end

#validates_attachment_presence_of(name, options = {}) ⇒ Object



8
9
10
11
12
13
# File 'lib/bulldog/validations.rb', line 8

def validates_attachment_presence_of(name, options={})
  validates_each(name, options) do |record, attribute, attachment|
    attachment.present? && attachment.file_size > 0 or
      record.errors.add attribute, options[:message] || :attachment_blank
  end
end

#validates_attachment_type_of(name, options = {}) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/bulldog/validations.rb', line 35

def validates_attachment_type_of(name, options={})
  validates_each(name, options) do |record, attribute, attachment|
    if attachment.present?
      if (pattern = options[:matches])
        attachment.content_type =~ pattern or
          record.errors.add attribute, options[:message] || :attachment_wrong_type
      elsif (specifier = options[:is])
        if specifier.is_a?(Symbol)
          attachment_class = Attachment.class_from_type(specifier)
          attachment.is_a?(attachment_class) or
            record.errors.add attribute, options[:message] || :attachment_wrong_type
        else
          parse_mime_type = lambda do |string|
            mime_type, parameter_string = string.to_s.split(/;/)
            parameters = {}
            (parameter_string || '').split(/,/).each do |pair|
              name, value = pair.strip.split(/=/)
              parameters[name] = value
            end
            [mime_type, parameters]
          end

          expected_type, expected_parameters = parse_mime_type.call(specifier)
          actual_type, actual_parameters = parse_mime_type.call(attachment.content_type)
          expected_type == actual_type && expected_parameters.all?{|k,v| actual_parameters[k] == v} or
            record.errors.add attribute, options[:message] || :wrong_type
        end
      end
    end
  end
end