Class: Sevgi::Derender::Document

Inherits:
Object
  • Object
show all
Defined in:
lib/sevgi/derender/document.rb

Class Attribute Summary collapse

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(content, &block) ⇒ Document

Returns a new instance of Document.



37
38
39
40
41
42
# File 'lib/sevgi/derender/document.rb', line 37

def initialize(content, &block)
  instance_exec(&block) if block

  @doc = self.class.parse(content)
  @decl = self.class.declaration(content)
end

Class Attribute Details

.cacheObject (readonly)

Returns the value of attribute cache.



11
12
13
# File 'lib/sevgi/derender/document.rb', line 11

def cache
  @cache
end

Instance Attribute Details

#declObject (readonly)

Returns the value of attribute decl.



35
36
37
# File 'lib/sevgi/derender/document.rb', line 35

def decl
  @decl
end

#docObject (readonly)

Returns the value of attribute doc.



35
36
37
# File 'lib/sevgi/derender/document.rb', line 35

def doc
  @doc
end

Class Method Details

.declaration(content) ⇒ Object



29
30
31
32
33
# File 'lib/sevgi/derender/document.rb', line 29

def self.declaration(content)
  return unless (content = content.lstrip).start_with?("<?xml ")

  content.split("\n").first
end

.load_file(path) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/sevgi/derender/document.rb', line 14

def self.load_file(path)
  entry = ::File.expand_path(F.qualify(path, "svg"))

  ArgumentError.("File not found: #{path}") unless ::File.exist?(entry)

  new(::File.read(entry)) do
    @doc = self.class.cache[entry] ||
      begin
        self.class.cache[entry] = self.class.parse(::File.read(entry))
      end
  end
end

.parse(content) ⇒ Object



27
# File 'lib/sevgi/derender/document.rb', line 27

def self.parse(content) = Nokogiri::XML(content)

Instance Method Details

#decompile(id = nil) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/sevgi/derender/document.rb', line 44

def decompile(id = nil)
  if id
    if (found = doc.xpath("//*[@id='#{id}']") || []).empty?
      ArgumentError.("No such element with id '#{id}' in document")
    end

    found.first
  else
    doc.root
  end => element

  Node.new(element, pres)
end

#presObject



58
59
60
61
62
63
# File 'lib/sevgi/derender/document.rb', line 58

def pres
  @pres ||= [].tap do |lines|
    lines.append(*doc.children.take_while { |node| node != doc.root }.map(&:to_xml))
    lines.unshift(decl) unless lines.first == decl
  end
end