Class: ConfigToolkit::KeyValueWriter

Inherits:
Writer
  • Object
show all
Defined in:
lib/configtoolkit/keyvaluewriter.rb

Overview

This class implements the Writer interface for key-value configuration files.

See KeyValue.txt for more details about the key-value configuration format.

Defined Under Namespace

Classes: Visitor

Instance Method Summary collapse

Methods inherited from Writer

#create_containing_object_hash

Constructor Details

#initialize(stream, config = KeyValueConfig::DEFAULT_CONFIG) ⇒ KeyValueWriter

Description:

This constructs a KeyValueWriter instance for a key-value format described by config for stream, where stream is either a file name (a String) or an IO object.

Parameters:

stream

A file name (String) or an IO object. If stream is a file name, then the KeyValueWriter will open the associated file.

config

A KeyValueConfig that defines the format of the key-value output that this instance can write



31
32
33
34
35
36
37
38
39
# File 'lib/configtoolkit/keyvaluewriter.rb', line 31

def initialize(stream, config = KeyValueConfig::DEFAULT_CONFIG)
  if(stream.class == String)
    @stream = File.open(stream, "w")
  else
    @stream = stream
  end

  @config = config
end

Instance Method Details

#require_symbol_parameter_names?Boolean

Returns:

Returns true, since the KeyValueWriter requires Symbol parameter names in the Hash passed to write.

Returns:



46
47
48
# File 'lib/configtoolkit/keyvaluewriter.rb', line 46

def require_symbol_parameter_names?
  return true
end

#write(config_hash, containing_object_name) ⇒ Object

Description:

This method writes config_hash to the underlying stream.

Parameters:

config_hash

The configuration hash to write

containing_object_name

The configuration’s containing object name



126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
# File 'lib/configtoolkit/keyvaluewriter.rb', line 126

def write(config_hash, containing_object_name)
  #
  # Unfortunately, the Visitor cannot be used to write out the top level
  # of configuration parameters, because the top-level format is different
  # than the nested levels (the top-level *is* a hash, but is written
  # out without braces and with one element on each line; the top-level
  # also has a containing object name).
  #
  if(!containing_object_name.empty?())
    key_prefix = "#{containing_object_name.gsub(/\./, @config.object_delimiter)}#{@config.object_delimiter}"
  else
    key_prefix = ""
  end

  visitor = Visitor.new(@stream, @config)
  config_hash.each do |key, value|
    @stream << "#{key_prefix}#{key} #{@config.key_value_delimiter} "

    if(value.is_a?(Hash) || value.is_a?(Array))
      visitor.visit(value)
    else
      @stream << "#{value}"
    end

    @stream << "\n"
  end

  @stream.flush()
end