Class: RubySGF::SGF::Record

Inherits:
Object
  • Object
show all
Defined in:
lib/sgf/record.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(data = nil) ⇒ Record

Returns a new instance of Record.



11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/sgf/record.rb', line 11

def initialize(data = nil)
  @data = data
  if data
    @root = Record.create_tree(@data)
  else
    n = Node.new(nil)
    n.properties = Property::DEFAULTS.map do |name, value|
      Property.new(name, [value])
    end
    @root = n
  end
end

Instance Attribute Details

#dataObject (readonly)

Returns the value of attribute data.



9
10
11
# File 'lib/sgf/record.rb', line 9

def data
  @data
end

#infoObject (readonly)

Returns the value of attribute info.



9
10
11
# File 'lib/sgf/record.rb', line 9

def info
  @info
end

#rootObject (readonly)

Returns the value of attribute root.



9
10
11
# File 'lib/sgf/record.rb', line 9

def root
  @root
end

Class Method Details

.create_tree(str) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/sgf/record.rb', line 31

def create_tree(str)
  str = StringScanner.new(str)
  root_node = node = nil
  old_nodes = []
  until str.eos?
    case s = str.getch
    when "("
      old_nodes << node
      node = Node.new(node)
      root_node = node if node.root?
    when ";"
      # pass along all of the properties of the current node to Node for creation
      # we ignore ; ( ) chars inside property values
      node_text = str.scan(/[A-Z]+\[.*?\]\s*[;\(\)]/m).strip[0..-2]
      # look for all property names 
      property_names = node_text.scan(/((?:[A-Z]+)(?:[^\\]|))\[/).flatten
      $stderr << "Error around \"#{str.matched}\": multiple properties of the same type -- all but the first instance will be ignored\n" if property_names.uniq!
      properties = Property.create_many_from_raw(node_text, property_names)
      if node.properties.empty? # every node must have a property
        node.properties = properties
      else
        node = Node.new(node, properties)
      end
      str.pos -= 1 # move back before the ; or ( or )
    when ")"
      node = old_nodes.pop
    else
      next
    end # case
  end # until
  root_node
end

Instance Method Details

#to_sObject



24
25
26
# File 'lib/sgf/record.rb', line 24

def to_s
  @root.write_tree
end