Created
March 25, 2016 21:08
-
-
Save frank-who/1863b1e0928df868f8b8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Usage: | |
# <%= svg_sprites(Rails.root.join('app/assets/images/sprites/*.svg')) %> | |
# <%= svg_icon('icon--check-circle') %> | |
module SvgSpriteHelper | |
def svg_icon(icon, options={}) | |
options[:class] ||= [] | |
options[:class] = [icon] + options[:class].split(' ') | |
content_tag(:svg, options) do | |
content_tag(:use, nil, 'xlink:href'=>"##{icon}") | |
end | |
end | |
def svg_sprites(sprites, prefix=nil) | |
content_tag(:svg, style:'display:none') do | |
Dir.glob(sprites).each do |svg_file| | |
concat svg_to_symbol(svg_file, prefix) | |
end | |
end | |
end | |
def svg_to_symbol(svg_file, prefix=nil) | |
svg_doc = Nokogiri::HTML(open(svg_file)) { |config| config.noblanks } | |
# Fetch attributes | |
svg = svg_doc.at_css('svg') | |
icon_name = svg_file.gsub('.svg', '').split('/').last | |
icon_id = [prefix, icon_name].compact.join('/') | |
# Get icon | |
icon_data = svg.at_css("[id^='#{icon_id}']") | |
icon_data.remove_attribute('id') | |
content_tag(:symbol, icon_data.to_html.html_safe, { id: icon_name, viewBox: svg['viewbox'] }) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment