Created
November 16, 2016 20:12
-
-
Save frank-who/e567017110ebe55002e55769ad7c4360 to your computer and use it in GitHub Desktop.
SVG Glyph Helpers
This file contains hidden or 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
# app/lib/svg_glyph.rb | |
class SvgGlyph | |
CURRENT_COLOR = '#383838' | |
GLYPH_NS = 'glyphs' | |
GLYPH_PATH = "app/assets/images/#{GLYPH_NS}" | |
def self.h | |
ActionController::Base.helpers | |
end | |
def self.optimize(tag, filename, options={}) | |
svg_file = Rails.root.join(GLYPH_PATH, "#{filename}.svg") | |
return h.content_tag(:svg, h.content_tag(:text, "#{filename}.svg Not Found")) if !File.exist?(svg_file) | |
css_class = options.delete(:class) | |
glyph_name = filename.split('/').last | |
document = Nokogiri::XML(File.open(svg_file)) | |
document.remove_namespaces! | |
if tag.to_s == 'svg' | |
document.root[:class] = ['glyph', glyph_name, css_class].compact.join(' ') | |
document.root['aria-hidden'] = true | |
elsif tag.to_s == 'symbol' | |
document.root.name = 'symbol' | |
document.root[:id] = [filename.split('/').last, options.delete(:id)].compact.join('--') | |
end | |
document.to_html.gsub(CURRENT_COLOR, 'currentColor') | |
.gsub("#{GLYPH_NS}/", '') | |
.strip! | |
end | |
end |
This file contains hidden or 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
# app/helpers/svg_glyph_helper.rb | |
# Usage | |
# * Add the glyph sheet: `= glyph_sheet` | |
# * Reference an icon: `= glyph('#icon-id')` | |
module SvgGlyphHelper | |
def glyph(glyph, options={}) | |
text = options.delete(:text) | |
options[:class] = ['glyph', glyph.delete('#'), options.delete(:class)] | |
if glyph.match(/^\#/) | |
capture do | |
concat content_tag(:span, options) { | |
concat content_tag(:svg, class: 'glyph__img') { content_tag(:use, nil, 'xlink:href'=>glyph) } | |
} | |
concat content_tag(:span, text, class: 'glyph__text') if text | |
end | |
else | |
SvgGlyph.optimize(:svg, glyph, options).html_safe | |
end | |
end | |
def glyph_sheet | |
content_tag(:svg, id: 'glyphs', style: 'display:none', 'aria-hidden'=>true) do | |
Dir.glob(Rails.root.join(SvgGlyph::GLYPH_PATH, '*.svg')).each do |glyph| | |
concat SvgGlyph.optimize(:symbol, glyph.split('/').last.gsub('.svg', ''), {}).html_safe | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment