{"id":7783,"date":"2015-10-26T15:49:48","date_gmt":"2015-10-26T15:49:48","guid":{"rendered":"https:\/\/unknownerror.org\/index.php\/2015\/10\/26\/carrierwaveuploader-carrierwave\/"},"modified":"2015-10-26T15:49:48","modified_gmt":"2015-10-26T15:49:48","slug":"carrierwaveuploader-carrierwave","status":"publish","type":"post","link":"https:\/\/unknownerror.org\/index.php\/2015\/10\/26\/carrierwaveuploader-carrierwave\/","title":{"rendered":"carrierwaveuploader\/carrierwave"},"content":{"rendered":"<p>This gem provides a simple and extremely flexible way to upload files from Ruby applications. It works well with Rack based web applications, such as Ruby on Rails.<\/p>\n<p><img decoding=\"async\" src=\"http:\/\/travis-ci.org\/carrierwaveuploader\/carrierwave.svg?branch=master\" \/> <img decoding=\"async\" src=\"http:\/\/img.shields.io\/codeclimate\/github\/carrierwaveuploader\/carrierwave.svg\" \/><\/p>\n<blockquote>\n<p><strong><em>This README is for a branch which is still in development. Please switch to latest <code>0.x<\/code> branch for stable version.<\/em><\/strong><\/p>\n<\/blockquote>\n<h2>Information<\/h2>\n<h2>Getting Help<\/h2>\n<ul>\n<li>Please ask the community on Stack Overflow for help if you have any questions. Please do not post usage questions on the issue tracker.<\/li>\n<li>Please report bugs on the issue tracker but read the \u201cgetting help\u201d section in the wiki first.<\/li>\n<\/ul>\n<h2>Installation<\/h2>\n<p>Install the latest stable release:<\/p>\n<pre><code>$ gem install carrierwave\n<\/code><\/pre>\n<p>In Rails, add it to your Gemfile:<\/p>\n<pre><code>gem 'carrierwave'\n<\/code><\/pre>\n<p>Finally, restart the server to apply the changes.<\/p>\n<p>As of version 1.0.0 (forthcoming), CarrierWave requires Rails 4.0 or higher and Ruby 2.0 or higher. If you\u2019re on Rails 3, you should use v0.10.0.<\/p>\n<h2>Getting Started<\/h2>\n<p>Start off by generating an uploader:<\/p>\n<pre><code>rails generate uploader Avatar\n<\/code><\/pre>\n<p>this should give you a file in:<\/p>\n<pre><code>app\/uploaders\/avatar_uploader.rb\n<\/code><\/pre>\n<p>Check out this file for some hints on how you can customize your uploader. It should look something like this:<\/p>\n<pre><code>class AvatarUploader &lt; CarrierWave::Uploader::Base\n  storage :file\nend\n<\/code><\/pre>\n<p>You can use your uploader class to store and retrieve files like this:<\/p>\n<pre><code>uploader = AvatarUploader.new\n\nuploader.store!(my_file)\n\nuploader.retrieve_from_store!('my_file.png')\n<\/code><\/pre>\n<p>CarrierWave gives you a <code>store<\/code> for permanent storage, and a <code>cache<\/code> for temporary storage. You can use different stores, including filesystem and cloud storage.<\/p>\n<p>Most of the time you are going to want to use CarrierWave together with an ORM. It is quite simple to mount uploaders on columns in your model, so you can simply assign files and get going:<\/p>\n<h3>ActiveRecord<\/h3>\n<p>Make sure you are loading CarrierWave after loading your ORM, otherwise you\u2019ll need to require the relevant extension manually, e.g.:<\/p>\n<pre><code>require 'carrierwave\/orm\/activerecord'\n<\/code><\/pre>\n<p>Add a string column to the model you want to mount the uploader by creating a migration:<\/p>\n<pre><code>rails g migration add_avatar_to_users avatar:string\nrake db:migrate\n<\/code><\/pre>\n<p>Open your model file and mount the uploader:<\/p>\n<pre><code>class User &lt; ActiveRecord::Base\n  mount_uploader :avatar, AvatarUploader\nend\n<\/code><\/pre>\n<p>Now you can cache files by assigning them to the attribute, they will automatically be stored when the record is saved.<\/p>\n<pre><code>u = User.new\nu.avatar = params[:file] # Assign a file like this, or\n\n# like this\nFile.open('somewhere') do |f|\n  u.avatar = f\nend\n\nu.save!\nu.avatar.url # =&gt; '\/url\/to\/file.png'\nu.avatar.current_path # =&gt; 'path\/to\/file.png'\nu.avatar_identifier # =&gt; 'file.png'\n<\/code><\/pre>\n<h3>DataMapper, Mongoid, Sequel<\/h3>\n<p>Other ORM support has been extracted into separate gems:<\/p>\n<ul>\n<li>carrierwave-datamapper<\/li>\n<li>carrierwave-mongoid<\/li>\n<li>carrierwave-sequel<\/li>\n<\/ul>\n<p>There are more extensions listed in the wiki<\/p>\n<h2>Multiple file uploads<\/h2>\n<p><strong>Note:<\/strong> You must specify using the master branch to enable this feature:<\/p>\n<p><code>gem 'carrierwave', github:'carrierwaveuploader\/carrierwave'<\/code>.<\/p>\n<p>CarrierWave also has convenient support for multiple file upload fields.<\/p>\n<h3>ActiveRecord<\/h3>\n<p>Add a column which can store an array. This could be an array column or a JSON column for example. Your choice depends on what your database supports. For example, create a migration like this:<\/p>\n<pre><code>rails g migration add_avatars_to_users avatars:json\nrake db:migrate\n<\/code><\/pre>\n<p>Open your model file and mount the uploader:<\/p>\n<pre><code>class User &lt; ActiveRecord::Base\n  mount_uploaders :avatars, AvatarUploader\nend\n<\/code><\/pre>\n<p>Make sure your file input fields are set up as multiple file fields. For example in Rails you\u2019ll want to do something like this:<\/p>\n<pre><code>\n<\/code><\/pre>\n<p>Now you can cache files by assigning them to the attribute, they will automatically be stored when the record is saved.<\/p>\n<pre><code>u = User.new\nu.avatars = params[:files] # Assign an array of files like this\nu.avatars = [File.open('somewhere')] # or like this\nu.save!\nu.avatars[0].url # =&gt; '\/url\/to\/file.png'\nu.avatars[0].current_path # =&gt; 'path\/to\/file.png'\nu.avatars[0].identifier # =&gt; 'file.png'\n<\/code><\/pre>\n<h2>Changing the storage directory<\/h2>\n<p>In order to change where uploaded files are put, just override the <code>store_dir<\/code> method:<\/p>\n<pre><code>class MyUploader &lt; CarrierWave::Uploader::Base\n  def store_dir\n    'public\/my\/upload\/directory'\n  end\nend\n<\/code><\/pre>\n<p>This works for the file storage as well as Amazon S3 and Rackspace Cloud Files. Define <code>store_dir<\/code> as <code>nil<\/code> if you\u2019d like to store files at the root level.<\/p>\n<p>If you store files outside the project root folder, you may want to define <code>cache_dir<\/code> in the same way:<\/p>\n<pre><code>class MyUploader &lt; CarrierWave::Uploader::Base\n  def cache_dir\n    '\/tmp\/projectname-cache'\n  end\nend\n<\/code><\/pre>\n<h2>Securing uploads<\/h2>\n<p>Certain files might be dangerous if uploaded to the wrong location, such as php files or other script files. CarrierWave allows you to specify a white-list of allowed extensions.<\/p>\n<p>If you\u2019re mounting the uploader, uploading a file with the wrong extension will make the record invalid instead. Otherwise, an error is raised.<\/p>\n<pre><code>class MyUploader &lt; CarrierWave::Uploader::Base\n  def extension_white_list\n    %w(jpg jpeg gif png)\n  end\nend\n<\/code><\/pre>\n<h3>Filenames and unicode chars<\/h3>\n<p>Another security issue you should care for is the file names (see Ruby On Rails Security Guide). By default, CarrierWave provides only English letters, arabic numerals and some symbols as white-listed characters in the file name. If you want to support local scripts (Cyrillic letters, letters with diacritics and so on), you have to override <code>sanitize_regexp<\/code> method. It should return regular expression which would match all <em>non<\/em>-allowed symbols.<\/p>\n<pre><code>CarrierWave::SanitizedFile.sanitize_regexp = \/[^[:word:]\\.\\-\\+]\/\n<\/code><\/pre>\n<p>Also make sure that allowing non-latin characters won\u2019t cause a compatibility issue with a third-party plugins or client-side software.<\/p>\n<h2>Setting the content type<\/h2>\n<p>As of v0.10.0, the <code>mime-types<\/code> gem is a runtime dependency and the content type is set automatically. You no longer need to do this manually.<\/p>\n<h2>Adding versions<\/h2>\n<p>Often you\u2019ll want to add different versions of the same file. The classic example is image thumbnails. There is built in support for this*:<\/p>\n<p><em>Note:<\/em> You must have Imagemagick and MiniMagick installed to do image resizing. MiniMagick is a Ruby interface for Imagemagick which is a C program. This is why MiniMagick fails on \u2018bundle install\u2019 without Imagemagick installed.<\/p>\n<p>Some documentation refers to RMagick instead of MiniMagick but MiniMagick is recommended.<\/p>\n<p>To install Imagemagick on OSX with homebrew type the following:<\/p>\n<pre><code>$ brew install imagemagick\n<\/code><\/pre>\n<pre><code>class MyUploader &lt; CarrierWave::Uploader::Base\n  include CarrierWave::MiniMagick\n\n  process resize_to_fit: [800, 800]\n\n  version :thumb do\n    process resize_to_fill: [200,200]\n  end\n\nend\n<\/code><\/pre>\n<p>When this uploader is used, an uploaded image would be scaled to be no larger than 800 by 800 pixels. A version called thumb is then created, which is scaled and cropped to exactly 200 by 200 pixels. The uploader could be used like this:<\/p>\n<pre><code>uploader = AvatarUploader.new\nuploader.store!(my_file)                              # size: 1024x768\n\nuploader.url # =&gt; '\/url\/to\/my_file.png'               # size: 800x600\nuploader.thumb.url # =&gt; '\/url\/to\/thumb_my_file.png'   # size: 200x200\n<\/code><\/pre>\n<p>One important thing to remember is that process is called <em>before<\/em> versions are created. This can cut down on processing cost.<\/p>\n<p>It is possible to nest versions within versions:<\/p>\n<pre><code>class MyUploader &lt; CarrierWave::Uploader::Base\n\n  version :animal do\n    version :human\n    version :monkey\n    version :llama\n  end\nend\n<\/code><\/pre>\n<h3>Conditional versions<\/h3>\n<p>Occasionally you want to restrict the creation of versions on certain properties within the model or based on the picture itself.<\/p>\n<pre><code>class MyUploader &lt; CarrierWave::Uploader::Base\n\n  version :human, if: :is_human?\n  version :monkey, if: :is_monkey?\n  version :banner, if: :is_landscape?\n\nprivate\n\n  def is_human? picture\n    model.can_program?(:ruby)\n  end\n\n  def is_monkey? picture\n    model.favorite_food == 'banana'\n  end\n\n  def is_landscape? picture\n    image = MiniMagick::Image.open(picture.path)\n    image[:width] &gt; image[:height]\n  end\n\nend\n<\/code><\/pre>\n<p>The <code>model<\/code> variable points to the instance object the uploader is attached to.<\/p>\n<h3>Create versions from existing versions<\/h3>\n<p>For performance reasons, it is often useful to create versions from existing ones instead of using the original file. If your uploader generates several versions where the next is smaller than the last, it will take less time to generate from a smaller, already processed image.<\/p>\n<pre><code>class MyUploader &lt; CarrierWave::Uploader::Base\n\n  version :thumb do\n    process resize_to_fill: [280, 280]\n  end\n\n  version :small_thumb, from_version: :thumb do\n    process resize_to_fill: [20, 20]\n  end\n\nend\n<\/code><\/pre>\n<p>The option <code>:from_version<\/code> uses the file cached in the <code>:thumb<\/code> version instead of the original version, potentially resulting in faster processing.<\/p>\n<h2>Making uploads work across form redisplays<\/h2>\n<p>Often you\u2019ll notice that uploaded files disappear when a validation fails. CarrierWave has a feature that makes it easy to remember the uploaded file even in that case. Suppose your <code>user<\/code> model has an uploader mounted on <code>avatar<\/code> file, just add a hidden field called <code>avatar_cache<\/code> (don\u2019t forget to add it to the attr_accessible list as necessary). In Rails, this would look like this:<\/p>\n<pre><code>\n  <br \/>\n    My Avatar\n    \n    \n  <br \/><br \/>\n\n<\/code><\/pre>\n<p>It might be a good idea to show the user that a file has been uploaded, in the case of images, a small thumbnail would be a good indicator:<\/p>\n<pre><code>\n  <br \/>\n    My Avatar\n    \n    \n    \n  <br \/><br \/>\n\n<\/code><\/pre>\n<h2>Removing uploaded files<\/h2>\n<p>If you want to remove a previously uploaded file on a mounted uploader, you can easily add a checkbox to the form which will remove the file when checked.<\/p>\n<pre><code>\n  <br \/>\n    My Avatar\n    \n    \n  <br \/><br \/>\n\n  <br \/>\n    \n      \n      Remove avatar\n    \n  <br \/><br \/>\n\n<\/code><\/pre>\n<p>If you want to remove the file manually, you can call <code>remove_avatar!<\/code>, then save the object.<\/p>\n<pre><code>@user.remove_avatar!\n@user.save\n#=&gt; true\n<\/code><\/pre>\n<h2>Uploading files from a remote location<\/h2>\n<p>Your users may find it convenient to upload a file from a location on the Internet via a URL. CarrierWave makes this simple, just add the appropriate attribute to your form and you\u2019re good to go:<\/p>\n<pre><code>\n  <br \/>\n    My Avatar URL:\n    \n    \n  <br \/><br \/>\n\n<\/code><\/pre>\n<p>If you\u2019re using ActiveRecord, CarrierWave will indicate invalid URLs and download failures automatically with attribute validation errors. If you aren\u2019t, or you disable CarrierWave\u2019s <code>validate_download<\/code> option, you\u2019ll need to handle those errors yourself.<\/p>\n<h2>Providing a default URL<\/h2>\n<p>In many cases, especially when working with images, it might be a good idea to provide a default url, a fallback in case no file has been uploaded. You can do this easily by overriding the <code>default_url<\/code> method in your uploader:<\/p>\n<pre><code>class MyUploader &lt; CarrierWave::Uploader::Base\n  def default_url(*args)\n    \"\/images\/fallback\/\" + [version_name, \"default.png\"].compact.join('_')\n  end\nend\n<\/code><\/pre>\n<p>Or if you are using the Rails asset pipeline:<\/p>\n<pre><code>class MyUploader &lt; CarrierWave::Uploader::Base\n  def default_url(*args)\n    ActionController::Base.helpers.asset_path(\"fallback\/\" + [version_name, \"default.png\"].compact.join('_'))\n  end\nend\n<\/code><\/pre>\n<h2>Recreating versions<\/h2>\n<p>You might come to a situation where you want to retroactively change a version or add a new one. You can use the <code>recreate_versions!<\/code> method to recreate the versions from the base file. This uses a naive approach which will re-upload and process the specified version or all versions, if none is passed as an argument.<\/p>\n<p>When you are generating random unique filenames you have to call <code>save!<\/code> on the model after using <code>recreate_versions!<\/code>. This is necessary because <code>recreate_versions!<\/code> doesn\u2019t save the new filename to the database. Calling <code>save!<\/code> yourself will prevent that the database and file system are running out of sync.<\/p>\n<pre><code>instance = MyUploader.new\ninstance.recreate_versions!(:thumb, :large)\n<\/code><\/pre>\n<p>Or on a mounted uploader:<\/p>\n<pre><code>User.find_each do |user|\n  user.avatar.recreate_versions!\nend\n<\/code><\/pre>\n<p>Note: <code>recreate_versions!<\/code> will throw an exception on records without an image. To avoid this, scope the records to those with images or check if an image exists within the block. If you\u2019re using ActiveRecord, recreating versions for a user avatar might look like this:<\/p>\n<pre><code>User.find_each do |user|\n  user.avatar.recreate_versions! if user.avatar?\nend\n<\/code><\/pre>\n<h2>Configuring CarrierWave<\/h2>\n<p>CarrierWave has a broad range of configuration options, which you can configure, both globally and on a per-uploader basis:<\/p>\n<pre><code>CarrierWave.configure do |config|\n  config.permissions = 0666\n  config.directory_permissions = 0777\n  config.storage = :file\nend\n<\/code><\/pre>\n<p>Or alternatively:<\/p>\n<pre><code>class AvatarUploader &lt; CarrierWave::Uploader::Base\n  permissions 0777\nend\n<\/code><\/pre>\n<p>If you\u2019re using Rails, create an initializer for this:<\/p>\n<pre><code>config\/initializers\/carrierwave.rb\n<\/code><\/pre>\n<p>If you want CarrierWave to fail noisily in development, you can change these configs in your environment file:<\/p>\n<pre><code>CarrierWave.configure do |config|\n  config.ignore_integrity_errors = false\n  config.ignore_processing_errors = false\n  config.ignore_download_errors = false\nend\n<\/code><\/pre>\n<h2>Testing with CarrierWave<\/h2>\n<p>It\u2019s a good idea to test your uploaders in isolation. In order to speed up your tests, it\u2019s recommended to switch off processing in your tests, and to use the file storage. In Rails you could do that by adding an initializer with:<\/p>\n<pre><code>if Rails.env.test? or Rails.env.cucumber?\n  CarrierWave.configure do |config|\n    config.storage = :file\n    config.enable_processing = false\n  end\nend\n<\/code><\/pre>\n<p>Remember, if you have already set <code>storage :something<\/code> in your uploader, the <code>storage<\/code> setting from this initializer will be ignored.<\/p>\n<p>If you need to test your processing, you should test it in isolation, and enable processing only for those tests that need it.<\/p>\n<p>CarrierWave comes with some RSpec matchers which you may find useful:<\/p>\n<pre><code>require 'carrierwave\/test\/matchers'\n\ndescribe MyUploader do\n  include CarrierWave::Test::Matchers\n\n  before do\n    MyUploader.enable_processing = true\n    @uploader = MyUploader.new(@user, :avatar)\n\n    File.open(path_to_file) do |f|\n      @uploader.store!(f)\n    end\n  end\n\n  after do\n    MyUploader.enable_processing = false\n    @uploader.remove!\n  end\n\n  context 'the thumb version' do\n    it \"should scale down a landscape image to be exactly 64 by 64 pixels\" do\n      @uploader.thumb.should have_dimensions(64, 64)\n    end\n  end\n\n  context 'the small version' do\n    it \"should scale down a landscape image to fit within 200 by 200 pixels\" do\n      @uploader.small.should be_no_larger_than(200, 200)\n    end\n  end\n\n  it \"should make the image readable only to the owner and not executable\" do\n    @uploader.should have_permissions(0600)\n  end\nend\n<\/code><\/pre>\n<p>Setting the enable_processing flag on an uploader will prevent any of the versions from processing as well. Processing can be enabled for a single version by setting the processing flag on the version like so:<\/p>\n<pre><code>@uploader.thumb.enable_processing = true\n<\/code><\/pre>\n<h2>Fog<\/h2>\n<p>If you want to use fog you must add in your CarrierWave initializer the following lines<\/p>\n<pre><code>config.fog_provider = 'fog' # 'fog\/aws' etc. Defaults to 'fog'\nconfig.fog_credentials = { ... } # Provider specific credentials\n<\/code><\/pre>\n<h2>Using Amazon S3<\/h2>\n<p>Fog AWS is used to support Amazon S3. Ensure you have it in your Gemfile:<\/p>\n<pre><code>gem \"fog-aws\"\n<\/code><\/pre>\n<p>You\u2019ll need to provide your fog_credentials and a fog_directory (also known as a bucket) in an initializer. For the sake of performance it is assumed that the directory already exists, so please create it if need be. You can also pass in additional options, as documented fully in lib\/carrierwave\/storage\/fog.rb. Here\u2019s a full example:<\/p>\n<pre><code>CarrierWave.configure do |config|\n  config.fog_provider = 'fog\/aws'                        # required\n  config.fog_credentials = {\n    provider:              'AWS',                        # required\n    aws_access_key_id:     'xxx',                        # required\n    aws_secret_access_key: 'yyy',                        # required\n    region:                'eu-west-1',                  # optional, defaults to 'us-east-1'\n    host:                  's3.example.com',             # optional, defaults to nil\n    endpoint:              'https:\/\/s3.example.com:8080' # optional, defaults to nil\n  }\n  config.fog_directory  = 'name_of_directory'                          # required\n  config.fog_public     = false                                        # optional, defaults to true\n  config.fog_attributes = { 'Cache-Control' =&gt; \"max-age=#{365.day.to_i}\" } # optional, defaults to {}\nend\n<\/code><\/pre>\n<p>In your uploader, set the storage to :fog<\/p>\n<pre><code>class AvatarUploader &lt; CarrierWave::Uploader::Base\n  storage :fog\nend\n<\/code><\/pre>\n<p>That\u2019s it! You can still use the <code>CarrierWave::Uploader#url<\/code> method to return the url to the file on Amazon S3.<\/p>\n<h2>Using Rackspace Cloud Files<\/h2>\n<p>Fog is used to support Rackspace Cloud Files. Ensure you have it in your Gemfile:<\/p>\n<pre><code>gem \"fog\"\n<\/code><\/pre>\n<p>You\u2019ll need to configure a directory (also known as a container), username and API key in the initializer. For the sake of performance it is assumed that the directory already exists, so please create it if need be.<\/p>\n<p>Using a US-based account:<\/p>\n<pre><code>CarrierWave.configure do |config|\n  config.fog_provider = \"fog\/rackspace\/storage\"   # optional, defaults to \"fog\"\n  config.fog_credentials = {\n    provider:           'Rackspace',\n    rackspace_username: 'xxxxxx',\n    rackspace_api_key:  'yyyyyy',\n    rackspace_region:   :ord                      # optional, defaults to :dfw\n  }\n  config.fog_directory = 'name_of_directory'\nend\n<\/code><\/pre>\n<p>Using a UK-based account:<\/p>\n<pre><code>CarrierWave.configure do |config|\n  config.fog_provider = \"fog\/rackspace\/storage\"   # optional, defaults to \"fog\"\n  config.fog_credentials = {\n    provider:           'Rackspace',\n    rackspace_username: 'xxxxxx',\n    rackspace_api_key:  'yyyyyy',\n    rackspace_auth_url: Fog::Rackspace::UK_AUTH_ENDPOINT,\n    rackspace_region:   :lon\n  }\n  config.fog_directory = 'name_of_directory'\nend\n<\/code><\/pre>\n<p>You can optionally include your CDN host name in the configuration. This is <em>highly<\/em> recommended, as without it every request requires a lookup of this information.<\/p>\n<pre><code>config.asset_host = \"http:\/\/c000000.cdn.rackspacecloud.com\"\n<\/code><\/pre>\n<p>In your uploader, set the storage to :fog<\/p>\n<pre><code>class AvatarUploader &lt; CarrierWave::Uploader::Base\n  storage :fog\nend\n<\/code><\/pre>\n<p>That\u2019s it! You can still use the <code>CarrierWave::Uploader#url<\/code> method to return the url to the file on Rackspace Cloud Files.<\/p>\n<h2>Using Google Storage for Developers<\/h2>\n<p>Fog is used to support Google Storage for Developers. Ensure you have it in your Gemfile:<\/p>\n<pre><code>gem \"fog-google\"\n<\/code><\/pre>\n<p>You\u2019ll need to configure a directory (also known as a bucket), access key id and secret access key in the initializer. For the sake of performance it is assumed that the directory already exists, so please create it if need be.<\/p>\n<p>Sign up here and get your credentials here under the section \u201cInteroperable Access\u201d.<\/p>\n<pre><code>CarrierWave.configure do |config|\n  config.fog_provider = 'fog-google'                        # required\n  config.fog_credentials = {\n    provider:                         'Google',\n    google_storage_access_key_id:     'xxxxxx',\n    google_storage_secret_access_key: 'yyyyyy'\n  }\n  config.fog_directory = 'name_of_directory'\nend\n<\/code><\/pre>\n<p>In your uploader, set the storage to :fog<\/p>\n<pre><code>class AvatarUploader &lt; CarrierWave::Uploader::Base\n  storage :fog\nend\n<\/code><\/pre>\n<p>That\u2019s it! You can still use the <code>CarrierWave::Uploader#url<\/code> method to return the url to the file on Google.<\/p>\n<h2>Optimized Loading of Fog<\/h2>\n<p>Since Carrierwave doesn\u2019t know which parts of Fog you intend to use, it will just load the entire library (unless you use e.g. [<code>fog-aws<\/code>, <code>fog-google<\/code>] instead of fog proper). If you prefer to load fewer classes into your application, you need to load those parts of Fog yourself <em>before<\/em> loading CarrierWave in your Gemfile. Ex:<\/p>\n<pre><code>gem \"fog\", \"~&gt; 1.27\", require: \"fog\/rackspace\/storage\"\ngem \"carrierwave\"\n<\/code><\/pre>\n<p>A couple of notes about versions:<\/p>\n<ul>\n<li>This functionality was introduced in Fog v1.20.<\/li>\n<li>This functionality is slated for CarrierWave v1.0.0.<\/li>\n<\/ul>\n<p>If you\u2019re not relying on Gemfile entries alone and are requiring \u201ccarrierwave\u201d anywhere, ensure you require \u201cfog\/rackspace\/storage\u201d before it. Ex:<\/p>\n<pre><code>require \"fog\/rackspace\/storage\"\nrequire \"carrierwave\"\n<\/code><\/pre>\n<p>Beware that this specific require is only needed when working with a fog provider that was not extracted to its own gem yet. A list of the extracted providers can be found in the page of the <code>fog<\/code> organizations here.<\/p>\n<p>When in doubt, inspect <code>Fog.constants<\/code> to see what has been loaded.<\/p>\n<h2>Dynamic Asset Host<\/h2>\n<p>The <code>asset_host<\/code> config property can be assigned a proc (or anything that responds to <code>call<\/code>) for generating the host dynamically. The proc-compliant object gets an instance of the current <code>CarrierWave::Storage::Fog::File<\/code> or <code>CarrierWave::SanitizedFile<\/code> as its only argument.<\/p>\n<pre><code>CarrierWave.configure do |config|\n  config.asset_host = proc do |file|\n    identifier = # some logic\n    \"http:\/\/#{identifier}.cdn.rackspacecloud.com\"\n  end\nend\n<\/code><\/pre>\n<h2>Using RMagick<\/h2>\n<p>If you\u2019re uploading images, you\u2019ll probably want to manipulate them in some way, you might want to create thumbnail images for example. CarrierWave comes with a small library to make manipulating images with RMagick easier, you\u2019ll need to include it in your Uploader:<\/p>\n<pre><code>class AvatarUploader &lt; CarrierWave::Uploader::Base\n  include CarrierWave::RMagick\nend\n<\/code><\/pre>\n<p>The RMagick module gives you a few methods, like <code>CarrierWave::RMagick#resize_to_fill<\/code> which manipulate the image file in some way. You can set a <code>process<\/code> callback, which will call that method any time a file is uploaded. There is a demonstration of convert here. Convert will only work if the file has the same file extension, thus the use of the filename method.<\/p>\n<pre><code>class AvatarUploader &lt; CarrierWave::Uploader::Base\n  include CarrierWave::RMagick\n\n  process resize_to_fill: [200, 200]\n  process convert: 'png'\n\n  def filename\n    super.chomp(File.extname(super)) + '.png' if original_filename.present?\n  end\nend\n<\/code><\/pre>\n<p>Check out the manipulate! method, which makes it easy for you to write your own manipulation methods.<\/p>\n<h2>Using MiniMagick<\/h2>\n<p>MiniMagick is similar to RMagick but performs all the operations using the \u2018mogrify\u2019 command which is part of the standard ImageMagick kit. This allows you to have the power of ImageMagick without having to worry about installing all the RMagick libraries.<\/p>\n<p>See the MiniMagick site for more details:<\/p>\n<p>https:\/\/github.com\/minimagick\/minimagick<\/p>\n<p>And the ImageMagick command line options for more for whats on offer:<\/p>\n<p>http:\/\/www.imagemagick.org\/script\/command-line-options.php<\/p>\n<p>Currently, the MiniMagick carrierwave processor provides exactly the same methods as for the RMagick processor.<\/p>\n<pre><code>class AvatarUploader &lt; CarrierWave::Uploader::Base\n  include CarrierWave::MiniMagick\n\n  process resize_to_fill: [200, 200]\nend\n<\/code><\/pre>\n<h2>Using Filemagic<\/h2>\n<p>Filemagic is a gem that provides Ruby bindings to the magic library.<\/p>\n<p>Since magic is writtern in C, modules using Filemagic are optional and don\u2019t work with JRuby.<\/p>\n<h3>Extract the actual content-type<\/h3>\n<p>You can use the <code>MagicMimeTypes<\/code> processor to extract the actual content-type of the uploaded file.<\/p>\n<p>For example, a user can upload a file named <code>file.png<\/code> but its actual content type may be JPEG.<\/p>\n<p>Below you can see an example usage of <code>MagicMimeTypes<\/code> processor.<\/p>\n<pre><code>class AvatarUploader &lt; CarrierWave::Uploader::Base\n  include CarrierWave::MagicMimeTypes\n\n  process :set_content_type\nend\n<\/code><\/pre>\n<h3>Validate with the actual content-type<\/h3>\n<p>You can use the <code>MagicMimeWhitelist<\/code> mixin to validate uploaded files given a regexp to match the allowed content types.<\/p>\n<p>Let\u2019s say we need an uploader that accepts only images.<\/p>\n<p>This can be done like this<\/p>\n<pre><code>class AvatarUploader &lt; CarrierWave::Uploader::Base\n  include CarrierWave::Uploader::MagicMimeWhitelist\n\n  # Override it to your needs.\n  # By default it returns nil and the validator allows every\n  # content-type.\n  def whitelist_mime_type_pattern\n    \/image\\\/\/\n  end\nend\n<\/code><\/pre>\n<p>There is also a <code>MagicMimeBlacklist<\/code> mixin to validate uploaded files given a rexp to match prohibited content types.<\/p>\n<p>Let\u2019s say we need an uploader that reject json files.<\/p>\n<p>This can be done like this<\/p>\n<pre><code>class NoJsonUploader &lt; CarrierWave::Uploader::Base\n  include CarrierWave::Uploader::MagicMimeBlacklist\n\n  # Override it to your needs.\n  # By default it returns nil and the validator allows every\n  # content-type.\n  def blacklist_mime_type_pattern\n    \/(application|text)\/json\/\n  end\nend\n<\/code><\/pre>\n<h2>Migrating from Paperclip<\/h2>\n<p>If you are using Paperclip, you can use the provided compatibility module:<\/p>\n<pre><code>class AvatarUploader &lt; CarrierWave::Uploader::Base\n  include CarrierWave::Compatibility::Paperclip\nend\n<\/code><\/pre>\n<p>See the documentation for <code>CarrierWave::Compatibility::Paperclip<\/code> for more details.<\/p>\n<p>Be sure to use mount_on to specify the correct column:<\/p>\n<pre><code>mount_uploader :avatar, AvatarUploader, mount_on: :avatar_file_name\n<\/code><\/pre>\n<h2>I18n<\/h2>\n<p>The Active Record validations use the Rails i18n framework. Add these keys to your translations file:<\/p>\n<pre><code>errors:\n  messages:\n    carrierwave_processing_error: \"Cannot resize image.\"\n    carrierwave_integrity_error: \"Not an image.\"\n    carrierwave_download_error: \"Couldn't download image.\"\n    extension_white_list_error: \"You are not allowed to upload %{extension} files, allowed types: %{allowed_types}\"\n    extension_black_list_error: \"You are not allowed to upload %{extension} files, prohibited types: %{prohibited_types}\"\n<\/code><\/pre>\n<h2>Large files<\/h2>\n<p>By default, CarrierWave copies an uploaded file twice, first copying the file into the cache, then copying the file into the store. For large files, this can be prohibitively time consuming.<\/p>\n<p>You may change this behavior by overriding either or both of the <code>move_to_cache<\/code> and <code>move_to_store<\/code> methods:<\/p>\n<pre><code>class MyUploader &lt; CarrierWave::Uploader::Base\n  def move_to_cache\n    true\n  end\n\n  def move_to_store\n    true\n  end\nend\n<\/code><\/pre>\n<p>When the <code>move_to_cache<\/code> and\/or <code>move_to_store<\/code> methods return true, files will be moved (instead of copied) to the cache and store respectively.<\/p>\n<p>This has only been tested with the local filesystem store.<\/p>\n<h2>Skipping ActiveRecord callbacks<\/h2>\n<p>By default, mounting an uploader into an ActiveRecord model will add a few callbacks. For example, this code:<\/p>\n<pre><code>class User\n  mount_uploader :avatar, AvatarUploader\nend\n<\/code><\/pre>\n<p>Will add these callbacks:<\/p>\n<pre><code>after_save :store_avatar!\nbefore_save :write_avatar_identifier\nafter_commit :remove_avatar!, on: :destroy\nafter_commit :\"mark_remove_avatar_false\", on: :update\nafter_save :\"store_previous_changes_for_avatar\"\nafter_commit :remove_previously_stored_avatar, on: :update\n<\/code><\/pre>\n<p>If you want to skip any of these callbacks (eg. you want to keep the existing avatar, even after uploading a new one), you can use ActiveRecord\u2019s <code>skip_callback<\/code> method.<\/p>\n<pre><code>class User\n  mount_uploader :avatar, AvatarUploader\n  skip_callback :commit, :after, :remove_previously_stored_avatar\nend\n<\/code><\/pre>\n<h2>Contributing to CarrierWave<\/h2>\n<p>See CONTRIBUTING.md<\/p>\n<h2>License<\/h2>\n<p>Copyright \u00a9 2008-2015 Jonas Nicklas<\/p>\n<p>Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \u201cSoftware\u201d), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:<\/p>\n<p>The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.<\/p>\n<p>THE SOFTWARE IS PROVIDED \u201cAS IS\u201d, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>This gem provides a simple and extremely flexible way to upload files from Ruby applications. It works well with Rack based web applications, such as Ruby on Rails. This README is for a branch which is still in development. Please switch to latest 0.x branch for stable version. Information Getting Help Please ask the community [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[],"class_list":["post-7783","post","type-post","status-publish","format-standard","hentry","category-uncategorized"],"_links":{"self":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts\/7783","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/comments?post=7783"}],"version-history":[{"count":0,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts\/7783\/revisions"}],"wp:attachment":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/media?parent=7783"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/categories?post=7783"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/tags?post=7783"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}