Class: Paperclip::Attachment

Inherits:
Object
  • Object
show all
Defined in:
lib/paperclip/attachment.rb

Overview

The Attachment class manages the files for a given attachment. It saves when the model saves, deletes when the model is destroyed, and processes the file upon assignment.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, instance, options = {}) ⇒ Attachment

Creates an Attachment object. name is the name of the attachment, instance is the ActiveRecord object instance it’s attached to, and options is the same as the hash passed to has_attached_file.



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/paperclip/attachment.rb', line 23

def initialize name, instance, options = {}
  @name              = name
  @instance          = instance

  options = self.class.default_options.merge(options)

  @url               = options[:url]
  @path              = options[:path]
  @styles            = options[:styles]
  @default_url       = options[:default_url]
  @validations       = options[:validations]
  @default_style     = options[:default_style]
  @storage           = options[:storage]
  @whiny_thumbnails  = options[:whiny_thumbnails]
  @options           = options
  @queued_for_delete = []
  @queued_for_write  = {}
  @errors            = []
  @validation_errors = nil
  @dirty             = false

  normalize_style_definition
  initialize_storage

  logger.info("[paperclip] Paperclip attachment #{name} on #{instance.class} initialized.")
end

Instance Attribute Details

#default_styleObject (readonly)

Returns the value of attribute default_style.



18
19
20
# File 'lib/paperclip/attachment.rb', line 18

def default_style
  @default_style
end

#instanceObject (readonly)

Returns the value of attribute instance.



18
19
20
# File 'lib/paperclip/attachment.rb', line 18

def instance
  @instance
end

#nameObject (readonly)

Returns the value of attribute name.



18
19
20
# File 'lib/paperclip/attachment.rb', line 18

def name
  @name
end

#stylesObject (readonly)

Returns the value of attribute styles.



18
19
20
# File 'lib/paperclip/attachment.rb', line 18

def styles
  @styles
end

Class Method Details

.default_optionsObject



6
7
8
9
10
11
12
13
14
15
16
# File 'lib/paperclip/attachment.rb', line 6

def self.default_options
  @default_options ||= {
    :url           => "/:attachment/:id/:style/:basename.:extension",
    :path          => ":merb_root/public/:attachment/:id/:style/:basename.:extension",
    :styles        => {},
    :default_url   => "/:attachment/:style/missing.png",
    :default_style => :original,
    :validations   => [],
    :storage       => :filesystem
  }
end

.interpolationsObject

A hash of procs that are run during the interpolation of a path or url. A variable of the format :name will be replaced with the return value of the proc named “:name”. Each lambda takes the attachment and the current style as arguments. This hash can be added to with your own proc if necessary.



160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
# File 'lib/paperclip/attachment.rb', line 160

def self.interpolations
  @interpolations ||= {
    :merb_root   => lambda{|attachment,style| Merb.root },
    :class        => lambda do |attachment,style|
                       attachment.instance.class.name.underscore.pluralize
                     end,
    :basename     => lambda do |attachment,style|
                       attachment.original_filename.gsub(File.extname(attachment.original_filename), "")
                     end,
    :extension    => lambda do |attachment,style| 
                       ((style = attachment.styles[style]) && style.last) ||
                       File.extname(attachment.original_filename).gsub(/^\.+/, "")
                     end,
    :id           => lambda{|attachment,style| attachment.instance.id },
    :id_partition => lambda do |attachment, style|
                       ("%09d" % attachment.instance.id).scan(/\d{3}/).join("/")
                     end,
    :attachment   => lambda{|attachment,style| attachment.name.to_s.downcase.pluralize },
    :style        => lambda{|attachment,style| style || attachment.default_style },
  }
end

Instance Method Details

#assign(uploaded_file) ⇒ Object

What gets called when you call instance.attachment = File. It clears errors, assigns attributes, processes the file, and runs validations. It also queues up the previous file for deletion, to be flushed away on #save of its host. In addition to form uploads, you can also assign another Paperclip attachment:

new_user.avatar = old_user.avatar


55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/paperclip/attachment.rb', line 55

def assign uploaded_file
  %w(file_name).each do |field|
    unless @instance.class.column_names.include?("#{name}_#{field}")
      raise PaperclipError.new("#{self} model does not have required column '#{name}_#{field}'")
    end
  end

  if uploaded_file.is_a?(Paperclip::Attachment)
    uploaded_file = uploaded_file.to_file(:original)
  end

  return nil unless valid_assignment?(uploaded_file)
  logger.info("[paperclip] Assigning #{uploaded_file.inspect} to #{name}")

  queue_existing_for_delete
  @errors            = []
  @validation_errors = nil

  return nil if uploaded_file.nil?

  logger.info("[paperclip] Writing attributes for #{name}")
  @queued_for_write[:original]        = uploaded_file['tempfile']
  @instance[:"#{@name}_file_name"]    = uploaded_file['filename'].strip.gsub /[^\w\d\.\-]+/, '_'
  @instance[:"#{@name}_content_type"] = uploaded_file['content_type'].strip
  @instance[:"#{@name}_file_size"]    = uploaded_file['tempfile'].size.to_i
  @instance[:"#{@name}_updated_at"]   = Time.now

  @dirty = true

  post_process
ensure
  validate
end

#dirty?Boolean

Returns true if there are changes that need to be saved.

Returns:

  • (Boolean)


124
125
126
# File 'lib/paperclip/attachment.rb', line 124

def dirty?
  @dirty
end

#errorsObject

Returns an array containing the errors on this attachment.



119
120
121
# File 'lib/paperclip/attachment.rb', line 119

def errors
  @errors.compact.uniq
end

#file?Boolean

Returns:

  • (Boolean)


203
204
205
# File 'lib/paperclip/attachment.rb', line 203

def file?
  !original_filename.blank?
end

#original_filenameObject

Returns the name of the file as originally assigned, and as lives in the <attachment>_file_name attribute of the model.



146
147
148
# File 'lib/paperclip/attachment.rb', line 146

def original_filename
  instance[:"#{name}_file_name"]
end

#path(style = nil) ⇒ Object

Returns the path of the attachment as defined by the :path option. If the file is stored in the filesystem the path refers to the path of the file on disk. If the file is stored in S3, the path is the “key” part of the URL, and the :bucket option refers to the S3 bucket.



103
104
105
# File 'lib/paperclip/attachment.rb', line 103

def path style = nil #:nodoc:
  interpolate(@path, style)
end

#reprocess!Object

This method really shouldn’t be called that often. It’s expected use is in the paperclip:refresh rake task and that’s it. It will regenerate all thumbnails forcefully, by reobtaining the original file and going through the post-process again.



186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
# File 'lib/paperclip/attachment.rb', line 186

def reprocess!
  new_original = Tempfile.new("paperclip-reprocess")
  if old_original = to_file(:original)
    new_original.write( old_original.read )
    new_original.rewind

    @queued_for_write = { :original => new_original }
    post_process

    old_original.close if old_original.respond_to?(:close)

    save
  else
    true
  end
end

#saveObject

Saves the file, if there are no errors. If there are, it flushes them to the instance’s errors and returns false, cancelling the save.



130
131
132
133
134
135
136
137
138
139
140
141
142
# File 'lib/paperclip/attachment.rb', line 130

def save
  if valid?
    logger.info("[paperclip] Saving files for #{name}")
    flush_deletes
    flush_writes
    @dirty = false
    true
  else
    logger.info("[paperclip] Errors on #{name}. Not saving.")
    flush_errors
    false
  end
end

#to_s(style = nil) ⇒ Object

Alias to url



108
109
110
# File 'lib/paperclip/attachment.rb', line 108

def to_s style = nil
  url(style)
end

#updated_atObject



150
151
152
153
# File 'lib/paperclip/attachment.rb', line 150

def updated_at
  time = instance[:"#{name}_updated_at"]
  time && time.to_i
end

#url(style = default_style) ⇒ Object

Returns the public URL of the attachment, with a given style. Note that this does not necessarily need to point to a file that your web server can access and can point to an action in your app, if you need fine grained security. This is not recommended if you don’t need the security, however, for performance reasons.



94
95
96
97
# File 'lib/paperclip/attachment.rb', line 94

def url style = default_style
  url = original_filename.nil? ? interpolate(@default_url, style) : interpolate(@url, style)
  updated_at ? [url, updated_at].compact.join(url.include?("?") ? "&" : "?") : url
end

#valid?Boolean

Returns true if there are no errors on this attachment.

Returns:

  • (Boolean)


113
114
115
116
# File 'lib/paperclip/attachment.rb', line 113

def valid?
  validate
  errors.length == 0
end