Skip to content

Instantly share code, notes, and snippets.

@Kolenov
Forked from youngbrioche/images_helper.rb
Last active May 7, 2018 11:05
Show Gist options
  • Save Kolenov/5bdeee241e1bed85e11039e7af4685eb to your computer and use it in GitHub Desktop.
Save Kolenov/5bdeee241e1bed85e11039e7af4685eb to your computer and use it in GitHub Desktop.
Responsive images helper using srcset in Rails
# frozen_string_literal: true
module ImagesHelper
# Acts as a thin wrapper for image_tag and generates an srcset attribute for regular image tags
# for usage with responsive images polyfills like picturefill.js, supports asset pipeline path helpers.
#
# image_set_tag 'pic_1980.jpg', { 'pic_640.jpg' => '640w', 'pic_1024.jpg' => '1024w', 'pic_1980.jpg' => '1980w' }, sizes: '100vw', class: 'my-image'
# => <img src="/assets/ants_1980.jpg" srcset="/assets/pic_640.jpg 640w, /assets/pic_1024.jpg 1024w, /assets/pic_1980.jpg 1980w" sizes="100vw" class="my-image">
#
# image_set_tag 'logo-amzlenders.png', {'[email protected]' => '2x'}
# => <img srcset="/assets/[email protected] 2x" src="/assets/logo-amzlenders.png" alt="Logo amzlenders">
def image_set_tag(source, srcset = {}, options = {})
srcset = srcset.map { |src, size| "#{image_path(src)} #{size}" }.join(', ')
image_tag(source, options.merge(srcset: srcset))
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment