Skip to content

Instantly share code, notes, and snippets.

@danmartens
Last active August 29, 2015 13:58
Show Gist options
  • Save danmartens/10188369 to your computer and use it in GitHub Desktop.
Save danmartens/10188369 to your computer and use it in GitHub Desktop.
Picturefill Responsive Image Tag Rails Helper
###
# Example:
#
# module ProductImageHelper
# def product_image_tag(product, options={})
# image = product.images.first.attachment
#
# image_queries = [
# {
# src: image.url(:large_mobile_2x),
# media: [
# { 'min-resolution' => '192dpi' },
# { '-webkit-min-device-pixel-ratio' => 2 }
# ]
# },
# {
# src: image.url(:large),
# media: { 'min-width' => '640px' }
# },
# {
# src: image.url(:large_2x),
# media: [
# { 'min-width' => '640px', 'min-resolution' => '192dpi' },
# { 'min-width' => '640px', '-webkit-min-device-pixel-ratio' => 2 }
# ]
# }
# ]
#
# responsive_image_tag(image_queries, image.url(:large_mobile), options)
# end
# end
###
module ResponsiveImageHelper
class ResponsiveImageTag
def initialize(context, image_queries, fallback_src, options)
@context = context
@image_queries = image_queries
@fallback_src = fallback_src
@options = options
end
def render
context.content_tag(:span, {
:'data-picture' => true,
:'data-alt' => options[:alt],
:class => 'responsive-image'
}.merge(options)) {
[
context.content_tag(:span, nil, {
'data-src' => fallback_src
}),
image_queries.map {|i|
context.content_tag(:span, nil, {
'data-src' => i[:src],
'data-media' => build_media_query(i[:media])
})
}.join.html_safe,
context.content_tag(:noscript) {
context.image_tag(fallback_src, alt: options[:alt])
}
].join.html_safe
}
end
private
attr_reader :context, :image_queries, :fallback_src, :options
def build_media_query(query=nil)
case query
when Hash
query.each_with_object([]) {|(k, v), arr|
arr << "(#{k}: #{v})"
}.join(' and ')
when Array
query.map { |q| build_media_query(q) }.join(', ')
else
query
end
end
end
def responsive_image_tag(image_queries, fallback_src, options={})
ResponsiveImageTag.new(self, image_queries, fallback_src, options).render
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment