Class: PDK::Config::IniFile::IniFileImpl

Inherits:
Object
  • Object
show all
Defined in:
lib/pdk/config/ini_file.rb

Overview

Adapted from raw.githubusercontent.com/puppetlabs/puppet/6c257fc7827989c2af2901f974666f0f23611153/lib/puppet/settings/ini_file.rb rubocop:disable Style/RegexpLiteral rubocop:disable Style/PerlBackrefs rubocop:disable Style/RedundantSelf rubocop:disable Style/StringLiterals

Defined Under Namespace

Modules: LineNumber Classes: DefaultSection, Line, SectionLine, SettingLine

Constant Summary collapse

DEFAULT_SECTION_NAME =
'default_section_name'.freeze

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(lines = []) ⇒ IniFileImpl

Returns a new instance of IniFileImpl.



90
91
92
# File 'lib/pdk/config/ini_file.rb', line 90

def initialize(lines = [])
  @lines = lines
end

Class Method Details

.parse(config_fh) ⇒ Object



74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/pdk/config/ini_file.rb', line 74

def self.parse(config_fh)
  config = new([DefaultSection.new])
  config_fh.each_line do |line|
    case line.chomp
    when /^(\s*)\[([[:word:]]+)\](\s*)$/
      config.append(SectionLine.new($1, $2, $3))
    when /^(\s*)([[:word:]]+)(\s*=\s*)(.*?)(\s*)$/
      config.append(SettingLine.new($1, $2, $3, $4, $5))
    else
      config.append(Line.new(line))
    end
  end

  config
end

Instance Method Details

#append(line) ⇒ Object



121
122
123
124
# File 'lib/pdk/config/ini_file.rb', line 121

def append(line)
  line.previous = @lines.last
  @lines << line
end

#munge_value(value) ⇒ Object



114
115
116
117
118
119
# File 'lib/pdk/config/ini_file.rb', line 114

def munge_value(value)
  value = value.to_s unless value.is_a?(String)
  # Strip enclosing quotes
  value = value.slice(1...-1) if value.start_with?('"') && value.end_with?('"')
  value
end

#to_hashObject



94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
# File 'lib/pdk/config/ini_file.rb', line 94

def to_hash
  result = {}

  current_section_name = nil
  @lines.each do |line|
    if line.instance_of?(SectionLine)
      current_section_name = line.name
      result[current_section_name] = {}
    elsif line.instance_of?(SettingLine)
      if current_section_name.nil?
        result[line.name] = munge_value(line.value)
      else
        result[current_section_name][line.name] = munge_value(line.value)
      end
    end
  end

  result
end