Class: CarrierWave::Uploader

Inherits:
Object
  • Object
show all
Defined in:
lib/carrierwave/uploader.rb

Class Attribute Summary collapse

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(model = nil, mounted_as = nil) ⇒ Uploader

If a model is given as the first parameter, it will stored in the uploader, and available throught #model. Likewise, mounted_as stores the name of the column where this instance of the uploader is mounted. These values can then be used inside your uploader.

If you do not wish to mount your uploaders with the ORM extensions in -more then you can override this method inside your uploader.

Examples:

class MyUploader < CarrierWave::Uploader
  def store_dir
    File.join('public', 'files', mounted_as, model.permalink)
  end
end

Parameters:

  • model (Object) (defaults to: nil)

    Any kind of model object

  • mounted_as (Symbol) (defaults to: nil)

    The name of the column where this uploader is mounted



154
155
156
157
# File 'lib/carrierwave/uploader.rb', line 154

def initialize(model=nil, mounted_as=nil)
  @model = model
  @mounted_as = mounted_as
end

Class Attribute Details

.version_nameObject

Returns the value of attribute version_name.



89
90
91
# File 'lib/carrierwave/uploader.rb', line 89

def version_name
  @version_name
end

Instance Attribute Details

#fileObject (readonly)

class << self



134
135
136
# File 'lib/carrierwave/uploader.rb', line 134

def file
  @file
end

#modelObject (readonly)

class << self



134
135
136
# File 'lib/carrierwave/uploader.rb', line 134

def model
  @model
end

#mounted_asObject (readonly)

class << self



134
135
136
# File 'lib/carrierwave/uploader.rb', line 134

def mounted_as
  @mounted_as
end

Class Method Details

.generate_cache_idString

Generates a unique cache id for use in the caching system

Returns:

  • (String)

    a cache if in the format YYYYMMDD-HHMM-PID-RND



122
123
124
# File 'lib/carrierwave/uploader.rb', line 122

def generate_cache_id
  Time.now.strftime('%Y%m%d-%H%M') + '-' + Process.pid.to_s + '-' + ("%04d" % rand(9999))
end

.process(*args) ⇒ Object

Adds a processor callback which applies operations as a file is uploaded. The argument may be the name of any method of the uploader, expressed as a symbol, or a list of such methods, or a hash where the key is a method and the value is an array of arguments to call the method with

Examples:

class MyUploader < CarrierWave::Uploader
  process :sepiatone, :vignette
  process :scale => [200, 200]

  def sepiatone
    ...
  end

  def vignette
    ...
  end

  def scale(height, width)
    ...
  end
end

Parameters:

  • args (*Symbol, Hash{Symbol => Array[]})


40
41
42
43
44
45
46
47
48
49
50
# File 'lib/carrierwave/uploader.rb', line 40

def process(*args)
  args.each do |arg|
    if arg.is_a?(Hash)
      arg.each do |method, args|
        processors.push([method, args])
      end
    else
      processors.push([arg, []])
    end
  end
end

.processorsString

Returns a list of processor callbacks which have been declared for this uploader

Returns:

  • (String)


11
12
13
# File 'lib/carrierwave/uploader.rb', line 11

def processors
  @processors ||= []
end

.storage(storage = nil) ⇒ Class

Sets the storage engine to be used when storing files with this uploader. Can be any class that implements a #store!(CarrierWave::SanitizedFile) and a #retrieve! method. See lib/carrierwave/storage/file.rb for an example. Storage engines should be added to CarrierWave.config so they can be referred to by a symbol, which should be more convenient

If no argument is given, it will simply return the currently used storage engine.

Examples:

storage :file
storage CarrierWave::Storage::File
storage MyCustomStorageEngine

Parameters:

  • storage (Symbol, Class) (defaults to: nil)

    The storage engine to use for this uploader

Returns:

  • (Class)

    the storage engine to be used with this uploader



68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/carrierwave/uploader.rb', line 68

def storage(storage = nil)
  if storage.is_a?(Symbol)
    @storage = get_storage_by_symbol(storage)
    @storage.setup!
  elsif storage
    @storage = storage
    @storage.setup!
  elsif @storage.nil?
    # Get the storage from the superclass if there is one
    @storage = superclass.storage rescue nil
  end
  if @storage.nil?
    # If we were not able to find a store any other way, setup the default store
    @storage ||= get_storage_by_symbol(CarrierWave.config[:storage])
    @storage.setup!
  end
  return @storage
end

.storage=Class

Sets the storage engine to be used when storing files with this uploader. Can be any class that implements a #store!(CarrierWave::SanitizedFile) and a #retrieve! method. See lib/carrierwave/storage/file.rb for an example. Storage engines should be added to CarrierWave.config so they can be referred to by a symbol, which should be more convenient

If no argument is given, it will simply return the currently used storage engine.

Examples:

storage :file
storage CarrierWave::Storage::File
storage MyCustomStorageEngine

Parameters:

  • storage (Symbol, Class)

    The storage engine to use for this uploader

Returns:

  • (Class)

    the storage engine to be used with this uploader



87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
# File 'lib/carrierwave/uploader.rb', line 87

def storage(storage = nil)
  if storage.is_a?(Symbol)
    @storage = get_storage_by_symbol(storage)
    @storage.setup!
  elsif storage
    @storage = storage
    @storage.setup!
  elsif @storage.nil?
    # Get the storage from the superclass if there is one
    @storage = superclass.storage rescue nil
  end
  if @storage.nil?
    # If we were not able to find a store any other way, setup the default store
    @storage ||= get_storage_by_symbol(CarrierWave.config[:storage])
    @storage.setup!
  end
  return @storage
end

.version(name, &block) ⇒ Object

Adds a new version to this uploader

Parameters:

  • name (#to_sym)

    name of the version

  • &block (Proc)

    a block to eval on this version of the uploader



97
98
99
100
101
102
103
104
105
106
107
108
# File 'lib/carrierwave/uploader.rb', line 97

def version(name, &block)
  name = name.to_sym
  klass = Class.new(self)
  klass.version_name = name
  klass.class_eval(&block) if block
  versions[name] = klass
  class_eval <<-RUBY
    def #{name}
      versions[:#{name}]
    end
  RUBY
end

.versionsHash{Symbol => Class}

Returns a list of versions available for this uploader.

Returns:

  • (Hash{Symbol => Class})

    a list of versions available for this uploader



113
114
115
# File 'lib/carrierwave/uploader.rb', line 113

def versions
  @versions ||= {}
end

Instance Method Details

#blank?Boolean

Returns Whether the uploaded file is blank.

Returns:

  • (Boolean)

    Whether the uploaded file is blank



162
163
164
# File 'lib/carrierwave/uploader.rb', line 162

def blank?
  !file or file.empty?
end

#cache(new_file) ⇒ Object

Caches the given file unless a file has already been cached, stored or retrieved.

Parameters:

  • new_file (File, IOString, Tempfile)

    any kind of file object

Raises:



283
284
285
# File 'lib/carrierwave/uploader.rb', line 283

def cache(new_file)
  cache!(new_file) unless file
end

#cache!(new_file) ⇒ Object

Caches the given file. Calls process! to trigger any process callbacks.

Parameters:

  • new_file (File, IOString, Tempfile)

    any kind of file object

Raises:



293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
# File 'lib/carrierwave/uploader.rb', line 293

def cache!(new_file)
  new_file = CarrierWave::SanitizedFile.new(new_file)
  raise CarrierWave::FormNotMultipart if new_file.string?

  unless new_file.empty?
    self.cache_id = CarrierWave::Uploader.generate_cache_id unless cache_id

    @file = new_file

    @filename = new_file.filename
    self.original_filename = new_file.filename
  
    @file = @file.copy_to(cache_path)
    process!

    versions.each do |name, v|
      v.send(:cache_id=, cache_id)
      v.cache!(new_file)
    end
  end
end

#cache_dirString

Override this in your Uploader to change the directory where files are cached.

Returns:

  • (String)

    a directory



264
265
266
# File 'lib/carrierwave/uploader.rb', line 264

def cache_dir
  CarrierWave.config[:cache_dir]
end

#cache_nameString

Returns a String which uniquely identifies the currently cached file for later retrieval

Returns:

  • (String)

    a cache name, in the format YYYYMMDD-HHMM-PID-RND/filename.txt



273
274
275
# File 'lib/carrierwave/uploader.rb', line 273

def cache_name
  File.join(cache_id, [version_name, original_filename].compact.join('_')) if cache_id and original_filename
end

#current_pathString

Returns the path where the file is currently located.

Returns:

  • (String)

    the path where the file is currently located.



178
179
180
# File 'lib/carrierwave/uploader.rb', line 178

def current_path
  file.path if file.respond_to?(:path)
end

#filenameString

Override this in your Uploader to change the filename.

Be careful using record ids as filenames. If the filename is stored in the database the record id will be nil when the filename is set. Don’t use record ids unless you understand this limitation.

Do not use the version_name in the filename, as it will prevent versions from being loaded correctly.

Returns:

  • (String)

    a filename



230
231
232
# File 'lib/carrierwave/uploader.rb', line 230

def filename
  @filename
end

#identifierString

Returns a string that uniquely identifies the last stored file

Returns:

  • (String)

    uniquely identifies a file



214
215
216
# File 'lib/carrierwave/uploader.rb', line 214

def identifier
  file.identifier if file.respond_to?(:identifier)
end

#process!Object

Apply all process callbacks added through CarrierWave.process



169
170
171
172
173
# File 'lib/carrierwave/uploader.rb', line 169

def process!
  self.class.processors.each do |method, args|
    self.send(method, *args)
  end
end

#publicString

Returns the directory where files will be publically accessible.

Returns:

  • (String)

    the directory where files will be publically accessible



251
252
253
# File 'lib/carrierwave/uploader.rb', line 251

def public
  CarrierWave.config[:public]
end

#retrieve_from_cache(cache_name) ⇒ Object

Retrieves the file with the given cache_name from the cache, unless a file has already been cached, stored or retrieved.

Parameters:

  • cache_name (String)

    uniquely identifies a cache file



321
322
323
324
# File 'lib/carrierwave/uploader.rb', line 321

def retrieve_from_cache(cache_name)
  retrieve_from_cache!(cache_name) unless file
rescue CarrierWave::InvalidParameter
end

#retrieve_from_cache!(cache_name) ⇒ Object

Retrieves the file with the given cache_name from the cache.

Parameters:

  • cache_name (String)

    uniquely identifies a cache file

Raises:



332
333
334
335
336
337
# File 'lib/carrierwave/uploader.rb', line 332

def retrieve_from_cache!(cache_name)
  self.cache_id, self.original_filename = cache_name.split('/', 2)
  @filename = original_filename
  @file = CarrierWave::SanitizedFile.new(cache_path)
  versions.each { |name, v| v.retrieve_from_cache!(cache_name) }
end

#retrieve_from_store(identifier) ⇒ Object

Retrieves the file from the storage, unless a file has already been cached, stored or retrieved.

Parameters:

  • identifier (String)

    uniquely identifies the file to retrieve



389
390
391
392
# File 'lib/carrierwave/uploader.rb', line 389

def retrieve_from_store(identifier)
  retrieve_from_store!(identifier) unless file
rescue CarrierWave::InvalidParameter
end

#retrieve_from_store!(identifier) ⇒ Object

Retrieves the file from the storage.

Parameters:

  • identifier (String)

    uniquely identifies the file to retrieve



399
400
401
402
# File 'lib/carrierwave/uploader.rb', line 399

def retrieve_from_store!(identifier)
  @file = storage.retrieve!(self, identifier)
  versions.each { |name, v| v.retrieve_from_store!(identifier) }
end

#rootString

Returns the directory that is the root of the application.

Returns:

  • (String)

    the directory that is the root of the application



244
245
246
# File 'lib/carrierwave/uploader.rb', line 244

def root
  CarrierWave.config[:root]
end

#store(new_file) ⇒ Object

Stores the file by passing it to this Uploader’s storage engine, unless a file has already been cached, stored or retrieved.

If CarrierWave.config is true, it will first cache the file and apply any process callbacks before uploading it.

Parameters:

  • new_file (File, IOString, Tempfile)

    any kind of file object



363
364
365
# File 'lib/carrierwave/uploader.rb', line 363

def store(new_file)
  store!(new_file) unless file
end

#store!(new_file = nil) ⇒ Object

Stores the file by passing it to this Uploader’s storage engine.

If new_file is omitted, a previously cached file will be stored.

Parameters:

  • new_file (File, IOString, Tempfile) (defaults to: nil)

    any kind of file object



374
375
376
377
378
379
380
381
# File 'lib/carrierwave/uploader.rb', line 374

def store!(new_file=nil)
  cache!(new_file) if new_file
  if @file
    @file = storage.store!(self, @file)
    @cache_id = nil
    versions.each { |name, v| v.store!(new_file) }
  end
end

#store_dirString

Override this in your Uploader to change the directory where the file backend stores files.

Other backends may or may not use this method, depending on their specific needs.

Returns:

  • (String)

    a directory



350
351
352
# File 'lib/carrierwave/uploader.rb', line 350

def store_dir
  [CarrierWave.config[:store_dir], version_name].compact.join(File::Separator)
end

#urlString Also known as: to_s

Returns the location where this file is accessible via a url.

Returns:

  • (String)

    the location where this file is accessible via a url



199
200
201
202
203
204
205
# File 'lib/carrierwave/uploader.rb', line 199

def url
  if file.respond_to?(:url) and not file.url.blank?
    file.url
  elsif current_path
    File.expand_path(current_path).gsub(File.expand_path(public), '')
  end
end

#version_nameString

Returns the name of this version of the uploader.

Returns:

  • (String)

    the name of this version of the uploader



237
238
239
# File 'lib/carrierwave/uploader.rb', line 237

def version_name
  self.class.version_name
end

#versionsHash{Symbol => CarrierWave::Uploader}

Returns a hash mapping the name of each version of the uploader to an instance of it

Returns:



187
188
189
190
191
192
193
194
# File 'lib/carrierwave/uploader.rb', line 187

def versions
  return @versions if @versions
  @versions = {}
  self.class.versions.each do |name, klass|
    @versions[name] = klass.new(model, mounted_as)
  end
  @versions
end