Resizing
English | 日本語
Client and utilities for Resizing - an image hosting and transformation service.
Requirements
- Ruby 3.1.0 or later (tested against 3.1, 3.2, 3.3, 3.4 and 4.0)
- Rails 7.0 or later for the CarrierWave integration (tested against 7.0, 7.1, 7.2, 8.0 and 8.1)
- Faraday 1.x or 2.x (tested against 1.10 and the latest 2.x)
- CarrierWave 2.2.5 or later, or 3.x, for the CarrierWave integration (tested against 2.2 and 3.1)
The exact combinations exercised in CI are listed in .github/workflows/test.yml.
Support for a Ruby or Rails series that has reached upstream end-of-life may be dropped in
a minor release; such changes are announced in the release notes.
Installation
Add this line to your application's Gemfile:
gem 'resizing'And then execute:
$ bundle install
Or install it yourself as:
$ gem install resizing
Configuration
Resizing.configure = {
image_host: 'https://img.resizing.net',
project_id: 'your-project-id',
secret_token: 'your-secret-token'
}video_host is deprecated because the video API has been discontinued. It is ignored
when given, and referring to Configuration#video_host or
Configuration::DEFAULT_VIDEO_HOST emits a warning. It will be removed in a future version.
Usage
Basic Client Usage
# Initialize client
client = Resizing::Client.new
# Upload image to resizing
file = File.open('sample.jpg', 'r')
response = client.post(file)
# => {
# "id"=>"a4ed2bf0-a4cf-44fa-9c82-b53e581cb469",
# "project_id"=>"098a2a0d-0000-0000-0000-000000000000",
# "content_type"=>"image/jpeg",
# "latest_version_id"=>"LJY5bxBF7Ryxfr5kC1F.63W8bzp3pcUm",
# "latest_etag"=>"\"190143614e6c342637584f46f18f8c58\"",
# "created_at"=>"2020-05-15T15:33:10.711Z",
# "updated_at"=>"2020-05-15T15:33:10.711Z",
# "url"=>"/projects/098a2a0d-0000-0000-0000-000000000000/upload/images/a4ed2bf0-a4cf-44fa-9c82-b53e581cb469"
# }
# Generate transformation URL
image_id = response['id']
transformation_url = Resizing.url_from_image_id(image_id, nil, ['w_200', 'h_300'])
# => "https://img.resizing.net/projects/.../upload/images/.../w_200,h_300"Temporary images
An image uploaded with temporary: true is deleted by Resizing at its expires_at
unless it is confirmed before then. expires_in is the number of seconds until it
expires (Resizing's default when omitted).
response = client.post(file, content_type: 'image/jpeg', temporary: true, expires_in: 3600)
response['temporary'] # => true
response['expires_at'] # => "2020-05-15T16:33:10.711Z"
# Keep the image
client.confirm(response['id'])A temporary image can be fetched and transformed like any other image until it expires.
Confirming an image that is already confirmed succeeds without changing it; confirming
an expired or deleted image raises Resizing::APIError.
CarrierWave Integration
class ImageUploader < CarrierWave::Uploader::Base
include Resizing::CarrierWave
version :list_smallest do
process resize_to_fill: [200, 200]
end
end
class User
mount_uploader :image, ImageUploader
endprocess declares the transformation applied when the browser fetches the image URL, so
the processors are never run as local image processing on upload.
The URL is built as in plain CarrierWave: the processes of the uploader apply to the image, and a version adds its own processes after those of its parent.
class ImageUploader < CarrierWave::Uploader::Base
include Resizing::CarrierWave
process resize_to_limit: [1000]
version :thumb do
process resize_to_fill: [200, 200]
end
end
user.image.url # => ".../<public_id>/c_limit,w_1000"
user.image.url(:thumb) # => ".../<public_id>/c_limit,w_1000/c_fill,w_200,h_200"
user.image.thumb.url # => the same as user.image.url(:thumb)The supported processes are resize_to_limit, resize_to_fill, resize_to_fit and
transformation ({ quality:, format:, fetch_format: }). The if: / unless: conditions of process are
honoured. When the column is blank, url returns default_url of the requested version, as
in plain CarrierWave.
Difference from CarrierWave: conditions of process
The if: / unless: conditions of process are checked every time url is called, not
on upload. If a condition calls a method that reads information of the file, such as
file.content_type, a request to the metadata API of Resizing is needed, which takes time
when many URLs are built (e.g. on a list page). content_type is nil when the API fails.
The file given to a condition is not the image file on your machine either, so a
condition that opens the image, such as MiniMagick::Image.open(file.path), raises an
error every time url is called.
The uploader validations hooked on CarrierWave's :cache callbacks are checked before the
image is uploaded to Resizing:
class ImageUploader < CarrierWave::Uploader::Base
include Resizing::CarrierWave
def extension_allowlist
%w[jpg jpeg gif png]
end
def content_type_allowlist
[%r{\Aimage/}]
end
def size_range
0..(5 * 1024 * 1024)
end
endextension_denylist and content_type_denylist work the same way. A rejected file is not
uploaded, and the model becomes invalid with an error on the mounted column, as in plain
CarrierWave.
The extension checked by extension_allowlist / extension_denylist is derived from the
content type of the file whenever it is known, not from the file name. A file downloaded
from a Resizing URL (e.g. assigned through remote_<column>_url=) ends with the version
string, so its file name has no meaningful extension; the Content-Type of the response
is used instead. When the content type is unknown (application/octet-stream), the
extension of the file name is used as in plain CarrierWave.
Versions are not uploaded separately: a version only changes the transformation in the generated URL, so a single upload backs every version.
Cache
Assigning a file to the mounted column uploads it to Resizing as a temporary image, and saving the model confirms it. When the model is never saved, e.g. because a validation fails, the image is left unconfirmed and Resizing deletes it when it expires, so no orphan image is left behind.
When the transaction is rolled back, no image is left behind either, but how depends on the CarrierWave version:
- CarrierWave 2.x confirms the image after commit, so the image is left unconfirmed and Resizing deletes it when it expires
- CarrierWave 3.x confirms the image when the model is saved, before commit, and deletes it when the transaction is rolled back
The temporary image expires after Resizing's default period. Override cache_expires_in
(in seconds) to change it, e.g. when a form may be kept open for a long time:
class ImageUploader < CarrierWave::Uploader::Base
include Resizing::CarrierWave
def cache_expires_in
2.days.to_i
end
endMaking uploads work across form redisplays
As in plain CarrierWave, send <column>_cache back with the form, so that the image does
not need to be uploaded again when the form is shown again after a validation error.
Permit it along with the column in the strong parameters, or it is dropped:
<%= form_with model: @user do |form| %>
<%= form.file_field :image %>
<%= form.hidden_field :image_cache %>
<%= form.submit %>
<% end %>class UsersController < ApplicationController
def create
@user = User.new(user_params)
if @user.save
redirect_to @user
else
render :new, status: :unprocessable_entity
end
end
private
def user_params
params.require(:user).permit(:image, :image_cache)
end
end<column>_cache returns the public id of the temporary image while it is not confirmed.
Only a temporary image of the configured project that has not expired is restored from
it; anything else (such as a confirmed image) is ignored, as CarrierWave ignores an
invalid cache name.
Removing images
The image is deleted from Resizing when CarrierWave removes the file, so when it happens follows the CarrierWave version:
| Operation | CarrierWave 2.x | CarrierWave 3.x |
|---|---|---|
remove_<column>! |
deleted on save | deleted immediately |
Assigning nil or '' to the column |
ignored (the image is kept) | deleted on save |
| Assigning another image | the previous image is deleted on save | the previous image is deleted on save |
Assigning nil or '' is the one exception on CarrierWave 2.x: plain CarrierWave 2.x
deletes the file, but this gem keeps the image, and prints a warning because the image is
deleted after upgrading to CarrierWave 3.x. Use remove_<column>! to delete the image, or
leave the column unassigned to keep it.
Upgrading
To x.x.x (unreleased)
The CarrierWave URLs are now built as in plain CarrierWave (see CarrierWave Integration), which changes some URLs.
The processes of the uploader itself are now applied. They used to be ignored, and
only the processes inside a version block were added to the URL. Now they are added to
the URL of the image and of every version:
class ImageUploader < CarrierWave::Uploader::Base
include Resizing::CarrierWave
process resize_to_limit: [1000] # ignored before x.x.x
version :thumb do
process resize_to_fill: [200, 200]
end
end
# before x.x.x
user.image.url # => ".../<public_id>/"
user.image.url(:thumb) # => ".../<public_id>/c_fill,w_200,h_200"
# x.x.x
user.image.url # => ".../<public_id>/c_limit,w_1000"
user.image.url(:thumb) # => ".../<public_id>/c_limit,w_1000/c_fill,w_200,h_200"To keep the URLs as before, remove the processes outside version blocks. Removing them
does not change the URLs of the versions, as a version does not inherit the processes of
its parent uploader.
url with several versions means a nested version. url(:large, :blur) used to join
the transformations of the versions large and blur. It now means the version blur
defined inside large, as in CarrierWave, and raises ArgumentError when there is no such
version. To get the same URL, nest the version, or define a version with both processes:
version :large do
process resize_to_fill: [1000, 866]
version :blur do
process ... # added after the transformations of large
end
end
user.image.url(:large, :blur) # => ".../<public_id>/c_fill,w_1000,h_866/<blur>"Other changes:
-
model.image.thumb.url,versions[:thumb].urlandserializable_hash(to_json) now include the transformations of the version. They used to return the URL of the image without them. - An unknown version raises
ArgumentErrorinstead ofRuntimeError. -
default_urlis called on the uploader of the requested version with the arguments ofurl, soversion_nametells which version is asked for. - The
if:/unless:conditions ofprocessare now honoured. They used to be ignored and the transformation was always added, so the URL loses the transformation when the condition is false. An exception raised in a condition now makesurlandto_jsonfail. - The public method
build_urlis removed.
Development
Dev Container (recommended)
This repository ships a Dev Container so that everyone develops against the same Ruby / MySQL setup.
Requirements: Docker and either VS Code + the Dev Containers extension, or the
devcontainer CLI.
-
Open the repository in VS Code and run Dev Containers: Reopen in Container (or run
devcontainer up --workspace-folder .). -
bundle installand the MySQL wait are executed automatically by.devcontainer/post-create.sh. -
Inside the container:
$ bundle exec rake test # run the tests $ bundle exec rubocop # run the linter $ bin/console # interactive prompt
The container provides:
- Ruby managed by rbenv, so the version can be changed from inside the container (see below)
- MySQL 5.7 with the
resizing_gem_testdatabase, matching CI -
RAILS_VERSIONto test against another Rails version, matching theRAILS_VERSIONswitch in theGemfileand in CI. Unset, theGemfilepicks the newest supported Rails that runs on the current Ruby (8.1, or 7.2 on Ruby 3.1)
Gems are installed into a named volume (/usr/local/bundle). vendor/, .bundle/ and
.ruby-lsp/ are kept on their own volumes so that Ruby artifacts generated on the host do
not leak into the container through the bind mount: vendor/ holds gems whose native
extensions are built against the host's libraries, .bundle/config points BUNDLE_PATH
at it, and .ruby-lsp/ records which gems the Ruby LSP extension has installed. The host
copies are left untouched.
Changing the Ruby version
Ruby 3.1.7 is installed when the image is built, and .ruby-version is honoured on
container creation. To switch to another version from inside the container:
$ rbenv install 3.3.12
$ rbenv local 3.3.12 # writes .ruby-version (gitignored)
$ bundle installrbenv install needs no sudo; the build dependencies are already in the image. To
change the version the image ships with, set the RUBY_VERSION build arg in
.devcontainer/compose.yaml and rebuild.
Without a Dev Container
After checking out the repo, run bin/setup to install dependencies. Then, run rake test to run the tests. You can also run bin/console for an interactive prompt that will allow you to experiment.
The tests need a MySQL server. docker-compose.yml in the repository root starts a
suitable one (docker compose up -d mysql).
Each test process creates its own database (resizing_gem_test_<host>_<pid>) and drops it
when the run finishes, so several test processes can share one MySQL server without
breaking each other's tables. Databases left behind by killed processes are cleaned up on
the next run.
The connection defaults to root:secret@127.0.0.1:3306 and can be overridden with the
MYSQL_HOST, MYSQL_PORT, MYSQL_USER and MYSQL_PASSWORD environment variables.
Setting MYSQL_DATABASE uses that database as is and never drops it; in that case give
each concurrent test process a different name, otherwise they will overwrite each other's
tables.
To install this gem onto your local machine, run bundle exec rake install. To release a new version, update the version number in version.rb, and then run bundle exec rake release, which will create a git tag for the version, push git commits and tags, and push the .gem file to rubygems.org.
Contributing
Bug reports and pull requests are welcome on GitHub at https://github.com/jksy/resizing-gem.
License
The gem is available as open source under the terms of the MIT License.