Class: Purpur::Generator

Inherits:
Object
  • Object
show all
Defined in:
lib/purpur/generator.rb

Instance Method Summary collapse

Constructor Details

#initializeGenerator

Returns a new instance of Generator.



8
9
10
# File 'lib/purpur/generator.rb', line 8

def initialize
  @templates_dir  = File.expand_path('../../templates', __FILE__)
end

Instance Method Details

#filesObject



12
13
14
# File 'lib/purpur/generator.rb', line 12

def files
  Purpur.icons
end

#generate(template, destination_path) ⇒ Object



49
50
51
52
53
# File 'lib/purpur/generator.rb', line 49

def generate(template, destination_path)
  file = File.new(destination_path, 'w')
  file.write sprite(template)
  file.close
end

#iconsObject



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/purpur/generator.rb', line 20

def icons
  files.map do |name|
    file        = read_svg(name)
    doc         = Nokogiri::HTML::DocumentFragment.parse(file)

    doc.css('*').remove_attr('fill')

    svg         = doc.at_css('svg')
    viewbox     = svg['viewbox']
    g           = svg.search('g')
    container   = g.empty? ? svg : g

    shape       = container.children.map {|c| c.to_s}.join('')
    name        = File.basename(name, Purpur::ICON_EXTENTION)

    { name: name, viewbox: viewbox, shape: shape }
  end
end

#optimize(code, template) ⇒ Object



39
40
41
# File 'lib/purpur/generator.rb', line 39

def optimize(code, template)
  template == 'sprite.svg' ? code.gsub(/$\s+/, '') : code
end

#read_svg(filename) ⇒ Object



16
17
18
# File 'lib/purpur/generator.rb', line 16

def read_svg(filename)
  File.read(filename)
end

#sprite(template) ⇒ Object



43
44
45
46
47
# File 'lib/purpur/generator.rb', line 43

def sprite(template)
  view    = File.read File.join(@templates_dir, "#{template}.erb")
  result  = ERB.new(view).result(binding)
  optimize(result, template)
end