- Notifications
You must be signed in to change notification settings - Fork35
A gem for integrating imgix into Rails projects
License
imgix/imgix-rails
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
imgix-rails is a gem for integratingimgix into Ruby on Rails applications. It builds onimgix-rb to offer a few Rails-specific interfaces. It is tested under Ruby versions3.1,3.0,2.7, andjruby-9.2.11.0.
- Installation
- Usage
- Using With Image Uploading Libraries
- Upgrade Guides
- Development
- Contributing
- Code of Conduct
- License
Add this line to your application's Gemfile:
gem'imgix-rails'
And then execute:
$ bundle
imgix-rails provides a few different hooks to work with your existing Rails application. All current methods are drop-in replacements for theimage_tag helper.
Before you get started, you will need to define your imgix configuration in yourconfig/application.rb, or in an environment-specific configuration file.
Rails.application.configuredoconfig.imgix={source:"assets.imgix.net"}end
The following configuration flags will be respected:
use_https: toggles the use of HTTPS. Defaults totruesource: a String or Array that specifies the imgix Source address. Should be in the form of"assets.imgix.net".srcset_width_tolerance: an optional numeric value determining the maximum tolerance allowable, between the downloaded dimensions and rendered dimensions of the image (default0.08i.e.8%).secure_url_token: an optional secure URL token found in your dashboard (https://dashboard.imgix.com) used for signing requestsinclude_library_param: toggles the inclusion of theixlibparameter. Defaults totrue.
In addition to the standard configuration flags, the following options can be used for multi-source support.
sources: a Hash of imgix source-secure_url_token key-value pairs. If the value for a source isnil, URLs generated for the corresponding source won't be secured.sourcesandsourcecannot be used together.default_source: optionally specify a default source for generating URLs.
Example:
Rails.application.configuredoconfig.imgix={sources:{"assets.imgix.net"=>"foobarbaz","assets2.imgix.net"=>nil,# Will generate unsigned URLs},default_source:"assets.imgix.net"}end
Theix_image_tag helper method makes it easy to pass parameters to imgix to handle resizing, cropping, etc. It also simplifies adding responsive imagery to your Rails app by automatically generating asrcset based on the parameters you pass. We talk a bit about using thesrcset attribute in an application in the following blog post:“Responsive Images withsrcset and imgix.”.
ix_image_tag generates<img> tags with a filled-outsrcset attribute that leans onimgix-rb to do the hard work. It also makes a variety of options available for customizing how thesrcset is generated. For example, if you already know the minimum or maximum number of physical pixels that this image will need to be displayed at, you can pass themin_width and/ormax_width options. This will result in a smaller, more tailoredsrcset.
ix_image_tag takes the following arguments:
source: An optional String indicating the source to be used. If unspecified:sourceor:default_sourcewill be used. If specified, the value must be defined in the config.path: The path or URL of the image to display.tag_options: HTML attributes to apply to the generatedimgelement. This is useful for adding class names, alt tags, etc.url_params: The imgix URL parameters to apply to this image. These will be applied to each URL in thesrcsetattribute, as well as the fallbacksrcattribute.srcset_options: A variety of options that allow for fine tuningsrcsetgeneration. More information on each of these modifiers can be found in theimgix-rb documentation. Any of the following can be passed as arguments:widths: An array of exact widths thatsrcsetpairs will be generated with.min_width: The minimum width thatsrcsetpairs will be generated with. Will be ignored ifwidthsare provided.max_width: The maximum width thatsrcsetpairs will be generated with. Will be ignored ifwidthsare provided.disable_variable_quality: Passtrueto disable variable quality parameters when generating asrcset(fixed-images only). In addition, imgix-rails will respect an overridingq(quality) parameter if one is provided throughurl_params.attribute_options: Allow you to change where imgix-rails rendersattributes. This can be helpful if you want to add lazy-loading.
<%= ix_image_tag('/unsplash/hotairballoon.jpg', url_params: { w: 300, h: 500, fit: 'crop', crop: 'right'}, tag_options: { alt: 'A hot air balloon on a sunny day' })%>
Will render out HTML like the following:
<imgalt="A hot air balloon on a sunny day"sizes="100vw"srcset=" https://assets.imgix.net/unsplash/hotairballoon.jpg?w=100&h=167&fit=crop&crop=right 100w, https://assets.imgix.net/unsplash/hotairballoon.jpg?w=200&h=333&fit=crop&crop=right 200w, … https://assets.imgix.net/unsplash/hotairballoon.jpg?w=2560&h=4267&fit=crop&crop=right 2560w"src="https://assets.imgix.net/unsplash/hotairballoon.jpg?w=300&h=500&fit=crop&crop=right">
Similarly
<%= ix_image_tag('assets2.imgix.net', '/unsplash/hotairballoon.jpg')%>
Will generate URLs usingassets2.imgix.net source.
We recommend leveraging this to generate powerful helpers within your application like the following:
defprofile_image_tag(user)ix_image_tag(user.profile_image_url,url_params:{w:100,h:200,fit:'crop'})end
Then rendering the portrait in your application is very easy:
<%= profile_image_tag(@user)%>
If you already know all the exact widths you need images for, you can specify that by passing thewidths option as an array. In this case, imgix-rails will only generatesrcset pairs for the specifiedwidths.
<%= ix_image_tag('/unsplash/hotairballoon.jpg', srcset_options: { widths: [320, 640, 960, 1280] }, tag_options: { alt: 'A hot air balloon on a sunny day' })%>
In cases where enough information is provided about an image's dimensions,ix_image_tag will instead build asrcset that will allow for an image to be served at different resolutions. The parameters taken into consideration when determining if an image is fixed-width arew,h, andar. By invokingix_image_tag with either a width or the height and aspect ratio (along withfit=crop, typically) provided, a different srcset will be generated for a fixed-size image instead.
<%= ix_image_tag('/unsplash/hotairballoon.jpg', url_params: {w: 1000})%>
Will render the following HTML:
<imgsrcset="https://assets.imgix.net/image.jpg?ixlib=rails-3.0.2&w=1000&dpr=1&q=75 1x,https://assets.imgix.net/image.jpg?ixlib=rails-3.0.2&w=1000&dpr=2&q=50 2x,https://assets.imgix.net/image.jpg?ixlib=rails-3.0.2&w=1000&dpr=3&q=35 3x,https://assets.imgix.net/image.jpg?ixlib=rails-3.0.2&w=1000&dpr=4&q=23 4x,https://assets.imgix.net/image.jpg?ixlib=rails-3.0.2&w=1000&dpr=5&q=20 5x"sizes="100vw"src="https://assets.imgix.net/image.jpg?ixlib=rails-3.0.2&w=1000">
Fixed image rendering will automatically append a variableq parameter mapped to eachdpr parameter when generating asrcset. This technique is commonly used to compensate for the increased filesize of high-DPR images. Since high-DPR images are displayed at a higher pixel density on devices, image quality can be lowered to reduce overall filesize without sacrificing perceived visual quality. For more information and examples of this technique in action, seethis blog post. This behavior will respect any overridingq value passed in viaurl_params and can be disabled altogether withsrcset_options: { disable_variable_quality: true }.
If you'd like to lazy load images, we recommend usinglazysizes. In order to use imgix-rails with lazysizes, you need to useattribute_options as well as settag_options[:src]:
<%= ix_image_tag('image.jpg', attribute_options: {src: "data-src",srcset: "data-srcset", sizes: "data-sizes"}, url_params: {w: 1000},tag_options: {src: "lqip.jpg"})%>
Will render the following HTML:
<imgdata-srcset="https://assets.imgix.net/image.jpg?ixlib=rails-3.0.2&w=1000&dpr=1&q=75 1x,https://assets.imgix.net/image.jpg?ixlib=rails-3.0.2&w=1000&dpr=2&q=50 2x,https://assets.imgix.net/image.jpg?ixlib=rails-3.0.2&w=1000&dpr=3&q=35 3x,https://assets.imgix.net/image.jpg?ixlib=rails-3.0.2&w=1000&dpr=4&q=23 4x,https://assets.imgix.net/image.jpg?ixlib=rails-3.0.2&w=1000&dpr=5&q=20 5x"data-sizes="100vw"data-src="https://assets.imgix.net/image.jpg?ixlib=rails-3.0.2&w=1000"src="lqip.jpg">
Theix_picture_tag helper method makes it easy to generatepicture elements in your Rails app.picture elements are useful when an images needs to be art directed differently at different screen sizes.
ix_picture_tag takes the following arguments:
source: an optional String indicating the source to be used. If unspecified:sourceor:default_sourcewill be used. If specified, the value must be defined in the config.path: The path or URL of the image to display.tag_options: Any options to apply to the parentpictureelement. This is useful for adding class names, etc.img_tag_options: Any options to apply to the generatedimgelement. This can be useful to add analtattribute.url_params: Default imgix options. These will be used to generate a fallbackimgtag for older browsers, and used in eachsourceunless overridden bybreakpoints.breakpoints: A hash describing the variants. Each key must be a media query (e.g.(max-width: 880px)), and each value must be a hash of parameter overrides for that media query. Asourceelement will be generated for each breakpoint specified.srcset_options: A variety of options that allow for fine tuningsrcsetgeneration. More information on each of these modifiers can be found in theimgix-rb documentation. Any of the following can be passed as arguments:widths: An array of exact widths thatsrcsetpairs will be generated with.min_width: The minimum width thatsrcsetpairs will be generated with. Will be ignored ifwidthsare provided.max_width: The maximum width thatsrcsetpairs will be generated with. Will be ignored ifwidthsare provided.disable_variable_quality: Passtrueto disable variable quality parameters when generating asrcset(fixed-images only). In addition, imgix-rails will respect an overridingq(quality) parameter if one is provided throughurl_params.
<%= ix_picture_tag('bertandernie.jpg', tag_options: { class: 'a-picture-tag' }, img_tag_options: { alt: 'A picture of Bert and Ernie arguing' }, url_params: { w: 300, h: 300, fit: 'crop', }, breakpoints: { '(max-width: 640px)' => { url_params: { h: 100, }, tag_options: { sizes: 'calc(100vw - 20px)' } }, '(max-width: 880px)' => { url_params: { crop: 'right', }, tag_options: { sizes: 'calc(100vw - 20px - 50%)' } }, '(min-width: 881px)' => { url_params: { crop: 'left', }, tag_options: { sizes: '430px' } } })%>
To generate apicture element on a different source:
<%= ix_picture_tag('assets2.imgix.net', 'bertandernie.jpg', tag_options: {}, img_tag_options: {}, url_params: {}, breakpoints: { '(max-width: 640px)' => { url_params: { h: 100 }, tag_options: { sizes: 'calc(100vw - 20px)' } }, } )%>
Theix_image_url helper makes it easy to generate a URL to an image in your Rails app.
ix_image_url takes three arguments:
source: an optional String indicating the source to be used. If unspecified:sourceor:default_sourcewill be used. If specified, the value must be defined in the config.path: The path or URL of the image to display.options: The imgix URL parameters to apply to this image URL. Optionally, you can usedisable_path_encoding: falsefor disabling URL-encoding which will be applied by default.
<%= ix_image_url('/users/1/avatar.png', { w: 400, h: 300 })%><%= ix_image_url('assets2.imgix.net', '/users/1/avatar.png', { w: 400, h: 300, disable_path_encoding: true })%>
Will generate the following URLs:
https://assets.imgix.net/users/1/avatar.png?w=400&h=300https://assets2.imgix.net/users/1/avatar.png?w=400&h=300
Sinceix_image_url lives insideUrlHelper, it can also be used in places other than your views quite easily. This is useful for things such as including imgix URLs in JSON output from a serializer class.
includeImgix::Rails::UrlHelperputsix_image_url('/users/1/avatar.png',{w:400,h:300})# => https://assets.imgix.net/users/1/avatar.png?w=400&h=300
Alternatively, you can also use the imgixRuby client in the same way.
ix_image_url is also pulled in as a Sprockets helper, so you can generate imgix URLs in your asset pipeline files. For example, here's how it would work inside an.scss.erb file:
.something {background-image:url(<%=ix_image_url('a-background.png',{w:400,h:300})%>);}
imgix-rails plays well with image uploading libraries, because it just requires a URL and optional parameters as arguments. A good way to handle this interaction is by creating helpers that bridge between your uploading library of choice and imgix-rails. Below are examples of how this can work with some common libraries. Please submit an issue if you'd like to see specific examples for another!
Paperclip and CarrierWave can directly provide paths to uploaded images, so we can use them with imgix-rails without a bridge.
<%= ix_image_tag(@user.avatar.path, { auto: 'format', fit: 'crop', w: 500}) %>
Since Refile doesn't actually store URLs or paths in the database (instead using a "prefix" + image identifier), the basic setup is slightly different. In this case, we use a couple helpers that bridge between Refile and imgix-rails.
moduleImgixRefileHelperdefix_refile_image_url(obj,key, **opts)path=s3_path(obj,key)path ?ix_image_url(path,opts) :''enddefix_refile_image_tag(obj,key, **opts)path=s3_path(obj,key)path ?ix_image_tag(path,opts) :''endprivatedefs3_path(obj,key)refile_id=obj["#{key}_id"]s3_prefix=obj.send(key).try(:backend).instance_variable_get(:@prefix)s3_prefix ?"#{s3_prefix}/#{refile_id}" :nilendend
<%= ix_refile_image_tag(@blog_post, :hero_photo, {auto: 'format', fit: 'crop', w: 500}) %>
To set up imgix with ActiveStorage, first ensure that the remote source your ActiveStorage service is pointing to is the same as your imgix source — such as an s3 bucket.
config/storage.yml
service:S3access_key_id:<%= Rails.application.credentials.dig(:aws, :access_key_id) %>secret_access_key:<%= Rails.application.credentials.dig(:aws, :secret_access_key) %>region:us-east-1bucket:your_own_bucket
google:service:GCSproject:Project Namecredentials:<%= Rails.root.join("path/to/key.json") %>bucket:Bucket Name
Modify youractive_storage.service setting depending on what environment you are using. For example, to use Amazon s3 in production, make the following change:
config/environments/production.rb
config.active_storage.service=:amazon
To use Google GCS in production, configure the active storage service like so:
config.active_storage.service=:google
As you would normally with imgix-rails, configure your application to point to your imgix source:
config/application.rb
Rails.application.configuredoconfig.imgix={source:your_domain,use_https:true,include_library_param:true}end
Finally, the two can be used together by passing in the filename of the ActiveStorage blob into the imgix-rails helper function:
show.html.erb
<%= ix_image_tag(@your_model.image.key)%>
The v4.0.0 release of imgix-rails introduces a variety of improvements relating to how this gem handles and generatessrcset attributes. However, in releasing this version there are some significant interface/behavioral changes that users need to be aware of. Users should note that themin_width andmax_width fields (passed viatag_options), as well as thewidths field, have all been moved to their own encompassingsrcset_options field. This is done with the intention of providing a more organized and intuitive experience when fine-tuning howsrcset width pairs are generated. See the following example demonstrating this new pattern:
<%= ix_image_tag('/unsplash/hotairballoon.jpg', srcset_options: { min_width: 1000, max_width: 2500}, tag_options: { alt: 'A hot air balloon on a sunny day' })%>
For users migrating to version 4.0 or later, it is important that all srcset-related modifiers be passed viasrcset_options, as doing so throughtag_options orwidths directly will result in errors. For more details on these modifiers, please see theix_image_tag orix_picture_tag sections.
In addition to these changes, imgix-rails is now capable of producingfixed-image srcsets. Users should note that when certain dimension information is provided, imgix-rails will produce asrcset at different screen resolutions rather than the typical width pairs. This feature provides expanded functionality to cover moresrcset use cases that users can take advantage of. We are always happy to provide our users with more tools to assist them in their efforts to build out responsive images on the web.
After checking out the repo, runbin/setup to install dependencies. Then, runbin/console for an interactive prompt that will allow you to experiment.
To install this gem onto your local machine, runbundle exec rake install. To release a new version, update the version number inversion.rb, and then runbundle exec rake release to create a git tag for the version, push git commits and tags, and push the.gem file torubygems.org.
Users contributing to or participating in the development of this project are subject to the terms of imgix'sCode of Conduct.
About
A gem for integrating imgix into Rails projects
Topics
Resources
License
Code of conduct
Contributing
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.