module SassC::InlineSVG::Functions

Public Instance Methods

inline_svg(path, options = nil) click to toggle source
# File lib/sassc-inline-svg.rb, line 9
def inline_svg(path, options = nil)
  svg = read_file(path.value.strip)
  svg = replace_options(svg, options)
  SassC::Script::Value::String.new(encode_url(svg))
end

Private Instance Methods

encode_url(svg) click to toggle source
# File lib/sassc-inline-svg.rb, line 41
def encode_url(svg)
  encoded = CGI::escape(svg).gsub("+", "%20")
  "url('data:image/svg+xml;charset=utf-8," + encoded + "')"
end
find_rails_asset(path) click to toggle source
# File lib/sassc-inline-svg.rb, line 25
def find_rails_asset(path)
  source = Rails.application.assets || ::Sprockets::Railtie.build_environment(Rails.application)
  asset = source.find_asset(path)
  raise "File not found or cannot be read (Sprockets): #{path}" if asset.nil?
  asset.to_s
end
read_file(path) click to toggle source
# File lib/sassc-inline-svg.rb, line 17
def read_file(path)
  return find_rails_asset(path) if defined?(Rails) && Rails.application

  raise SassC::SyntaxError, "File not found or cannot be read (native): #{path}" unless File.readable?(path)

  File.open(path, 'rb') { |f| f.read }.strip
end
replace_options(svg, options) click to toggle source
# File lib/sassc-inline-svg.rb, line 32
def replace_options(svg, options)
  return svg if options.nil?

  options.value.each_pair do |k, v|
    svg.gsub!(k.value, v.value) if svg.include?(k.value)
  end
  svg
end