Skip to content

Instantly share code, notes, and snippets.

@jodyheavener
Created October 7, 2016 04:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jodyheavener/f34c20abda45b9f5e1091d5f8c4e4055 to your computer and use it in GitHub Desktop.
Save jodyheavener/f34c20abda45b9f5e1091d5f8c4e4055 to your computer and use it in GitHub Desktop.
Rails Helper to maintain SVGs and consistently output them in your views.
# Allows Rails views to output consistent inline SVG code
module SvgHelper
def svg(named, options={})
svg_data = svg_defs[named]
defaults = {
:verion => "1.1",
:role => "img",
:width => svg_data[:width],
:height => svg_data[:height],
:label => svg_data[:label]
}
defaults.merge!(options)
defaults[:viewBox] = defaults[:viewBox] || "0 0 #{defaults[:width]} #{defaults[:height]}"
defaults[:"aria-label"] = defaults[:"aria-label"] || defaults[:label]
raw(content_tag(:svg, raw(svg_data[:data]), defaults.except(:data, :label)))
end
private
def svg_defs
{
:thumb_up => {
:label => 'like',
:width => 48,
:height => 48,
:data => '<path d="M2 42h8V18H2v24zm44-22c0-2.21-1.79-4-4-4H29.37l1.91-9.14c.04-.2.07-.41.07-.63 0-.83-.34-1.58-.88-2.12L28.34 2 15.17 15.17C14.45 15.9 14 16.9 14 18v20c0 2.21 1.79 4 4 4h18c1.66 0 3.08-1.01 3.68-2.44l6.03-14.1c.18-.46.29-.95.29-1.46v-3.83l-.02-.02L46 20z"/>'
},
:thumb_down => {
:label => 'dislike',
:width => 48,
:height => 48,
:data => '<path d="M30 6H12c-1.66 0-3.08 1.01-3.68 2.44l-6.03 14.1C2.11 23 2 23.49 2 24v3.83l.02.02L2 28c0 2.21 1.79 4 4 4h12.63l-1.91 9.14c-.04.2-.07.41-.07.63 0 .83.34 1.58.88 2.12L19.66 46l13.17-13.17C33.55 32.1 34 31.1 34 30V10c0-2.21-1.79-4-4-4zm8 0v24h8V6h-8z"/>'
}
}
end
end
# <%= svg(:thumb_up) %>
# <%= svg(:thumb_down) %>
#
# Produces...
#
# <svg verion="1.1" role="img" aria-label="like" width="48" height="48" viewBox="0 0 48 48">
# <path d="M2 42h8V18H2v24zm44-22c0-2.21-1.79-4-4-4H29.37l1.91-9.14c.04-.2.07-.41.07-.63 0-.83-.34-1.58-.88-2.12L28.34 2 15.17 15.17C14.45 15.9 14 16.9 14 18v20c0 2.21 1.79 4 4 4h18c1.66 0 3.08-1.01 3.68-2.44l6.03-14.1c.18-.46.29-.95.29-1.46v-3.83l-.02-.02L46 20z"/>
# </svg>
#
# <svg verion="1.1" role="img" aria-label="dislike" width="48" height="48" viewBox="0 0 48 48">
# <path d="M30 6H12c-1.66 0-3.08 1.01-3.68 2.44l-6.03 14.1C2.11 23 2 23.49 2 24v3.83l.02.02L2 28c0 2.21 1.79 4 4 4h12.63l-1.91 9.14c-.04.2-.07.41-.07.63 0 .83.34 1.58.88 2.12L19.66 46l13.17-13.17C33.55 32.1 34 31.1 34 30V10c0-2.21-1.79-4-4-4zm8 0v24h8V6h-8z"/>
# </svg>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment