Skip to content

Instantly share code, notes, and snippets.

@henrik
Created February 11, 2015 07:57
Show Gist options
  • Save henrik/2ddcc6ab8c66e7c49305 to your computer and use it in GitHub Desktop.
Save henrik/2ddcc6ab8c66e7c49305 to your computer and use it in GitHub Desktop.
Rails image_set_tag_3x helper for srcset.
module ImagesHelper
# Example usage:
#
# image_set_tag_3x "foo_1x.png", alt: "foo"
#
# Will assume there is a 2x and 3x version and provide those automagically.
#
# Based on https://gist.github.com/mrreynolds/4fc71c8d09646567111f
def image_set_tag_3x(source, options = {})
srcset = [ 2, 3 ].map { |num|
name = source.sub("_1x.", "_#{num}x.")
"#{path_to_image(name)} #{num}x"
}.join(", ")
image_tag(source, options.merge(srcset: srcset))
end
end
# This is a Rails-less unit test.
require "spec_helper"
require "helpers/images_helper"
describe ImagesHelper, "#image_set_tag_3x" do
let(:helper) { Class.new { include ImagesHelper }.new }
it "generates an image tag" do
allow(helper).to receive(:path_to_image) { |x| "path/to/#{x}" }
expect(helper).to receive(:image_tag).with(
"foo_1x.png",
srcset: "path/to/foo_2x.png 2x, path/to/foo_3x.png 3x",
alt: "foo",
)
helper.image_set_tag_3x("foo_1x.png", alt: "foo")
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment