Class: Autoini::Section

Inherits:
Element show all
Includes:
InlineComment
Defined in:
lib/autoini/section.rb

Instance Attribute Summary collapse

Attributes included from InlineComment

#comment

Class Method Summary collapse

Instance Method Summary collapse

Methods included from InlineComment

included, #line_comment

Constructor Details

#initialize(title, *contents) ⇒ Section

Returns a new instance of Section.



8
9
10
11
12
# File 'lib/autoini/section.rb', line 8

def initialize(title, *contents)
  @title = title
  @lines = []
  self << contents
end

Instance Attribute Details

#linesObject (readonly)

Returns the value of attribute lines.



6
7
8
# File 'lib/autoini/section.rb', line 6

def lines
  @lines
end

#titleObject

Returns the value of attribute title.



5
6
7
# File 'lib/autoini/section.rb', line 5

def title
  @title
end

Class Method Details

.[](title, hash) ⇒ Object

Raises:

  • (ArgumentError)


14
15
16
17
# File 'lib/autoini/section.rb', line 14

def self.[](title, hash)
  raise ArgumentError, "must pass a hash" unless hash.is_a?(Hash)
  new title, *hash.map{ |k, v| Pair.new(k, v) }
end

.parse(line) ⇒ Object



61
62
63
# File 'lib/autoini/section.rb', line 61

def self.parse(line)
  Section.new(line[1]) if line.length == 3 && line[0] == '[' && line[2] == ']'
end

Instance Method Details

#<<(contents) ⇒ Object



19
20
21
22
23
24
25
26
# File 'lib/autoini/section.rb', line 19

def <<(contents)
  Autoini.wrap(contents).each do |c|
    unless c.is_a?(AbstractLine)
      raise ArgumentError, "#{c.class.name} must extend Autoini::AbstractLine"
    end
    @lines << c
  end
end

#==(e) ⇒ Object



36
37
38
39
40
# File 'lib/autoini/section.rb', line 36

def ==(e)
  e.is_a?(Section) && e.title == title && e.comment == comment &&
    e.lines.length == lines.length &&
    lines.map.with_index{ |l, i| e.lines[i] == l }.all?
end

#merge!(other_section) ⇒ Object



46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/autoini/section.rb', line 46

def merge!(other_section)
  unless other_section.is_a?(Section)
    raise ArgumentError, "must pass a Autoini::Section"
  end
  other_section.lines.each do |l|
    next unless l.is_a?(Pair)
    if p = pair(l.key)
      p.value = l.value
    else
      self << l
    end
  end
  self
end

#pair(key) ⇒ Object



42
43
44
# File 'lib/autoini/section.rb', line 42

def pair(key)
  lines.select{ |l| l.is_a?(Pair) && l.key.to_s == key.to_s }.first
end

#to_aObject



32
33
34
# File 'lib/autoini/section.rb', line 32

def to_a
  [title.to_sym, lines.map(&:to_a).reject(&:empty?).to_h]
end

#to_sObject



28
29
30
# File 'lib/autoini/section.rb', line 28

def to_s
  [line_comment("[#{title}]"), lines.map(&:to_s)].flatten.join(Autoini.newline)
end