Module: Autoini

Defined in:
lib/autoini.rb,
lib/autoini/pair.rb,
lib/autoini/comment.rb,
lib/autoini/element.rb,
lib/autoini/section.rb,
lib/autoini/version.rb,
lib/autoini/contents.rb,
lib/autoini/blank_line.rb,
lib/autoini/abstract_line.rb,
lib/autoini/inline_comment.rb

Defined Under Namespace

Modules: InlineComment Classes: AbstractLine, BlankLine, Comment, Contents, Element, Pair, Section

Constant Summary collapse

ESCAPE_CHAR =
'\\'
COMMENTS =
%w( # ; )
SPECIAL =
%w( = [ ] ) | [ESCAPE_CHAR] | COMMENTS
MAP_CHARS =
{ "\r" => '\\r', "\n" => '\\n' }
VERSION =
"0.2.0"

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.commentObject

Returns the value of attribute comment.



21
22
23
# File 'lib/autoini.rb', line 21

def comment
  @comment
end

.newlineObject

Returns the value of attribute newline.



21
22
23
# File 'lib/autoini.rb', line 21

def newline
  @newline
end

Class Method Details

.divide(text) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/autoini.rb', line 52

def divide(text)
  [].tap do |s|
    buffer = ''
    escaping = false
    text.each_char do |c|
      if escaping
        buffer << unescape_char(c)
        escaping = false
      elsif c == ESCAPE_CHAR
        escaping = true
      elsif SPECIAL.include?(c)
        s << buffer.strip unless buffer.strip.empty?
        s << c
        buffer = ''
      else
        buffer << c
      end
    end
    s << buffer.strip unless buffer.strip.empty?
  end
end

.escape(text) ⇒ Object



36
37
38
39
40
41
42
43
44
# File 'lib/autoini.rb', line 36

def escape(text)
  ''.tap do |b|
    text.to_s.each_char do |c|
      b << MAP_CHARS[c] and next if MAP_CHARS[c]
      b << '\\' if SPECIAL.include?(c)
      b << c
    end
  end
end

.merge(file, data) ⇒ Object



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

def merge(file, data)
  Contents.parse((File.open(file, 'rb', &:read) rescue nil))
    .merge!(Contents[data]).tap{ |c| File.write(file, c.to_s) }.to_h
end

.read(file) ⇒ Object



23
24
25
# File 'lib/autoini.rb', line 23

def read(file)
  Contents.hash(File.open(file, 'rb', &:read))
end

.unescape_char(char) ⇒ Object



46
47
48
49
50
# File 'lib/autoini.rb', line 46

def unescape_char(char)
  return char if SPECIAL.include?(char)
  MAP_CHARS.key("\\#{char}") ||
    raise(ArgumentError, "#{char.inspect} is not an unescapable character")
end

.wrap(array) ⇒ Object



74
75
76
77
78
79
80
81
82
83
# File 'lib/autoini.rb', line 74

def wrap(array)
  case array
  when nil
    []
  when Array
    array
  else
    [array]
  end
end

.write(file, data) ⇒ Object



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

def write(file, data)
  File.write(file, Contents[data].to_s)
end