Module: CarrierWave::Mount
- Included in:
- ActiveRecord, DataMapper
- Defined in:
- lib/carrierwave/mount.rb
Overview
If a Class is extended with this module, it gains the mount_uploader method, which is used for mapping attributes to uploaders and allowing easy assignment.
You can use mount_uploader with pretty much any class, however it is intended to be used with some kind of persistent storage, like an ORM. If you want to persist the uploaded files in a particular Class, it needs to implement a ‘read_uploader` and a `write_uploader` method.
Defined Under Namespace
Modules: Extension
Instance Method Summary collapse
-
#mount_uploader(column, uploader = nil, &block) ⇒ Object
Mounts the given uploader on the given column.
-
#uploaders ⇒ Hash{Symbol => CarrierWave}
What uploaders are mounted on which columns.
Instance Method Details
#mount_uploader(column, uploader = nil, &block) ⇒ Object
Mounts the given uploader on the given column. This means that assigning and reading from the column will upload and retrieve files. Supposing that a User class has an uploader mounted on image, you can assign and retrieve files like this:
@user.image # => <Uploader>
@user.image = some_file_object
@user.store_image!
@user.image.url # => '/some_url.png'
It is also possible (but not recommended) to ommit the uploader, which will create an anonymous uploader class. Passing a block to this method makes it possible to customize it. This can be convenient for brevity, but if there is any significatnt logic in the uploader, you should do the right thing and have it in its own file.
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 |
# File 'lib/carrierwave/mount.rb', line 66 def mount_uploader(column, uploader=nil, &block) unless uploader uploader = Class.new(CarrierWave::Uploader) uploader.class_eval(&block) end uploaders[column.to_sym] = uploader include CarrierWave::Mount::Extension class_eval <<-EOF, __FILE__, __LINE__+1 def #{column} # def image get_uploader(:#{column}) # get_uploader(:image) end # end # def #{column}=(new_file) # def image=(new_file) set_uploader(:#{column}, new_file) # set_uploader(:image, new_file) end # end # def #{column}_cache # def image_cache get_uploader_cache(:#{column}) # get_uploader_cache(:image) end # end # def #{column}_cache=(cache_name) # def image_cache=(cache_name) set_uploader_cache(:#{column}, cache_name) # set_uploader_cache(:image, cache_name) end # end # def store_#{column}! # def store_image! store_uploader!(:#{column}) # store_uploader!(:image) end # end EOF after_mount(column, uploader) if respond_to?(:after_mount) end |
#uploaders ⇒ Hash{Symbol => CarrierWave}
Returns what uploaders are mounted on which columns.
18 19 20 |
# File 'lib/carrierwave/mount.rb', line 18 def uploaders @uploaders ||= {} end |