Module: AttachIt::ClassMethods

Defined in:
lib/attach_it/attach_it.rb

Instance Method Summary collapse

Instance Method Details

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



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/attach_it/attach_it.rb', line 9

def has_attachment(name, options = {})
  options = options.symbolize_keys
  name = name.to_sym

  after_save     :save_attachments
  before_destroy :destroy_attachments

  key :"#{name}_file_name", String
  key :"#{name}_file_size", Integer
  key :"#{name}_content_type", String
  key :"#{name}_updated_at", Date

  define_method("#{name}=") do |file|
    information_for(name, options).assign(file)
  end

  define_method("#{name}") do
    information_for(name, options)
  end
  

  validates_each(name) do |record, attr, value|
    record.information_for(name, options).send(:flush_errors)
  end

end

#validates_attachment_content_type(name = nil, options = {}) ⇒ Object



56
57
58
59
60
61
62
63
64
65
# File 'lib/attach_it/attach_it.rb', line 56

def validates_attachment_content_type(name = nil, options = {})
  validation_options = options.dup
  allowed_types = [validation_options[:content_type]].flatten
  message = options[:message] || "is not one of #{allowed_types.join(", ")}"

  validates_inclusion_of :"#{name}_content_type",
                         :in        => allowed_types,
                         :message   => message,
                         :allow_nil => true
end

#validates_attachment_presence(name = nil, options = {}) ⇒ Object



49
50
51
52
53
54
# File 'lib/attach_it/attach_it.rb', line 49

def validates_attachment_presence(name = nil, options = {})
  message = options[:message] || "must be set"
  validates_presence_of :"#{name}_file_name",
                        :message   => message,
                        :if        => options[:if]
end

#validates_attachment_size(name = nil, options = {}) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/attach_it/attach_it.rb', line 36

def validates_attachment_size(name = nil, 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 size must be between :min and :max bytes"
  message = message.gsub(/:min/, min.to_s).gsub(/:max/, max.to_s)

  validates_inclusion_of :"#{name}_file_size",
                         :in        => range,
                         :message   => message,
                         :allow_nil => true
end