Class: PythonConfig::ConfigSection

Inherits:
Hash show all
Defined in:
lib/amp/dependencies/python_config.rb

Overview

ConfigSection

This is a simple section in a config document - treat it exactly like a hash, whose keys are the keys in the config, and whose value are the values in the config.

This is a separate class entirely because it has to handle the magical interpolation that allows this ini file:

[Awards]
output: Congratulations for winning %(prize)!
prize: the lottery

To result in:

config.sections["Awards"]["output"] == "Congratulations for winning the lottery!"

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from Hash

#get, #pick, with_keys

Constructor Details

#initialize(source) ⇒ ConfigSection

Returns a new instance of ConfigSection.



162
163
164
165
# File 'lib/amp/dependencies/python_config.rb', line 162

def initialize(source)
  @source_hash = source
  super(@source_hash)
end

Instance Attribute Details

#source_hashObject (readonly)

Returns the value of attribute source_hash.



161
162
163
# File 'lib/amp/dependencies/python_config.rb', line 161

def source_hash
  @source_hash
end

Instance Method Details

#[](*args) ⇒ Object

:nodoc:

Raises:

  • (ArgumentError)


167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
# File 'lib/amp/dependencies/python_config.rb', line 167

def [](*args) #:nodoc:
  raise ArgumentError.new("Must provide either 1 or 2 args") unless (1..3).include? args.size
  key = args[0]
  str = @source_hash[key]
  str = interpolate str
  if args.size == 3 && str.nil? || str == ""
    return args[2]
  end 
  return str if args.size == 1
  
  type = args[1]
  if type == Integer || type == Fixnum || type == Bignum
    result = str.to_i
  elsif type == Boolean
    result = str.downcase == "true"
  elsif type == Float
    result = str.to_f
  elsif type == Array
    result = str.split(",").map {|s| s.strip}
  elsif type == String
    result = str
  end
  return result if args.size == 2
  
  
  (str.nil? || str.strip == "") ? args[2] : result
end

#interpolate(str, cur_depth = 0) ⇒ Object

:nodoc:



195
196
197
198
199
200
201
# File 'lib/amp/dependencies/python_config.rb', line 195

def interpolate(str, cur_depth=0) #:nodoc:
  raise InterpolationTooDeepError.new("Interpolation too deep!") if cur_depth > PythonConfig::MAX_INTERPOLATION_DEPTH
  nextval = str
  nextval = str.gsub(/\%\((.*)\)/,@source_hash[$1]) if str =~ /%\((.*)\)/
  nextval = interpolate(nextval,cur_depth+1) if nextval =~ /%\((.*)\)/
  nextval
end

#to_sObject

:nodoc:



203
204
205
206
207
208
209
# File 'lib/amp/dependencies/python_config.rb', line 203

def to_s #:nodoc:
  output = ""
  @source_hash.each do |k,v|
    output << "#{k} = #{v.to_s.gsub(/\n/,"\n ")}" << "\n"
  end
  output
end