Class: SvgThang::ErbConverter

Inherits:
Object
  • Object
show all
Defined in:
lib/svgthang/erb_converter.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(default_classes: "", prefix: "") ⇒ ErbConverter

Returns a new instance of ErbConverter.



9
10
11
12
13
# File 'lib/svgthang/erb_converter.rb', line 9

def initialize(default_classes: "", prefix: "")
  @default_classes = default_classes
  @prefix = prefix
  @logger = Logger.new(STDOUT)
end

Instance Attribute Details

#default_classesObject (readonly)

Returns the value of attribute default_classes.



7
8
9
# File 'lib/svgthang/erb_converter.rb', line 7

def default_classes
  @default_classes
end

#loggerObject (readonly)

Returns the value of attribute logger.



7
8
9
# File 'lib/svgthang/erb_converter.rb', line 7

def logger
  @logger
end

#prefixObject (readonly)

Returns the value of attribute prefix.



7
8
9
# File 'lib/svgthang/erb_converter.rb', line 7

def prefix
  @prefix
end

Instance Method Details

#convert(source_path, target_path) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/svgthang/erb_converter.rb', line 15

def convert(source_path, target_path)
  contents = File.read(source_path)

  if !contents.start_with? "<svg"
    logger.error "#{source_path} doesn't appear to be an SVG file"
    return
  end

  logger.info "Converting #{source_path} to ERB template at #{target_path}"

  svg_doc = Oga.parse_html(contents)
  svg_doc.at_css("svg").set(
    "class", "#{default_classes} <%= defined?(classes) ? classes : nil %>")
  html = HTMLEntities.new.decode(svg_doc.to_xml)

  filename = "#{prefix}#{File.basename(target_path, ".svg")}.html.erb"
  new_target_path = Pathname.new(target_path).parent.join(filename)

  File.open(new_target_path, "w") do |f|
    f.write(html)
  end
end