Class: Samovar::Table

Inherits:
Object
  • Object
show all
Defined in:
lib/samovar/table.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(parent = nil, name: nil) ⇒ Table

Returns a new instance of Table.



16
17
18
19
20
# File 'lib/samovar/table.rb', line 16

def initialize(parent = nil, name: nil)
	@parent = parent
	@name = name
	@rows = {}
end

Class Method Details

.nested(klass, parent = nil) ⇒ Object



8
9
10
11
12
13
14
# File 'lib/samovar/table.rb', line 8

def self.nested(klass, parent = nil)
	if klass.superclass.respond_to?(:table)
		parent = klass.superclass.table
	end
	
	self.new(parent, name: klass.name)
end

Instance Method Details

#<<(row) ⇒ Object



38
39
40
41
42
43
44
45
# File 'lib/samovar/table.rb', line 38

def << row
	if existing_row = @rows[row.key] and existing_row.respond_to?(:merge!)
		existing_row.merge!(row)
	else
		# In the above case where there is an existing row, but it doensn't support being merged, we overwrite it. This preserves order.
		@rows[row.key] = row.dup
	end
end

#[](key) ⇒ Object



30
31
32
# File 'lib/samovar/table.rb', line 30

def [] key
	@rows[key]
end

#each(&block) ⇒ Object



34
35
36
# File 'lib/samovar/table.rb', line 34

def each(&block)
	@rows.each_value(&block)
end

#empty?Boolean

Returns:

  • (Boolean)


47
48
49
# File 'lib/samovar/table.rb', line 47

def empty?
	@rows.empty? && @parent&.empty?
end

#freezeObject



22
23
24
25
26
27
28
# File 'lib/samovar/table.rb', line 22

def freeze
	return self if frozen?
	
	@rows.freeze
	
	super
end

#merge_into(table) ⇒ Object



51
52
53
54
55
56
57
58
59
# File 'lib/samovar/table.rb', line 51

def merge_into(table)
	@parent&.merge_into(table)
	
	@rows.each_value do |row|
		table << row
	end
	
	return table
end

#mergedObject



61
62
63
64
65
66
67
# File 'lib/samovar/table.rb', line 61

def merged
	if @parent.nil? or @parent.empty?
		return self
	else
		merge_into(self.class.new)
	end
end

#parse(input, parent) ⇒ Object



73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/samovar/table.rb', line 73

def parse(input, parent)
	@rows.each do |key, row|
		next unless row.respond_to?(:parse)
		
		current = parent.send(key)
		
		result = row.parse(input, parent, current)
		if result != nil
			parent.public_send("#{row.key}=", result)
		end
	end
end

#usageObject



69
70
71
# File 'lib/samovar/table.rb', line 69

def usage
	@rows.each_value.collect(&:to_s).reject(&:empty?).join(' ')
end