class Mhc::Config::Base

Parse Key-Value object in YAML

Attributes

original_hash[R]

Public Class Methods

create_from_yaml_file(yaml_file) click to toggle source

attr_accessor :name

# File lib/mhc/config.rb, line 49
def self.create_from_yaml_file(yaml_file)
  yaml_string = File.open(File.expand_path(yaml_file)).read
  return create_from_yaml_string(yaml_string, yaml_file)
end
create_from_yaml_string(yaml_string, filename = nil) click to toggle source
# File lib/mhc/config.rb, line 54
def self.create_from_yaml_string(yaml_string, filename = nil)
  hash = YAML.load(yaml_string, filename) || {}
  return new(hash)
end
define_syntax(config) click to toggle source
# File lib/mhc/config.rb, line 59
def self.define_syntax(config)
  @syntax = Syntax.new(config)
  @syntax.keyword_symbols.each do |sym|
    attr_accessor sym # XXX: attr_reader is enough?
  end
end
new(hash = {}) click to toggle source
# File lib/mhc/config.rb, line 70
def initialize(hash = {})
  @original_hash = hash
  (hash || {}).each do |key, val|
    raise Mhc::ConfigurationError, "config syntax error (#{key})" unless syntax.keyword?(key)
    var = syntax.instance_variable_name(key)
    obj = create_subnode(key, val)
    instance_variable_set(var, obj)
  end
end
syntax() click to toggle source
# File lib/mhc/config.rb, line 66
def self.syntax
  return @syntax
end

Public Instance Methods

get_value(dot_separated_string = nil) click to toggle source
# File lib/mhc/config.rb, line 82
def get_value(dot_separated_string = nil)
  if dot_separated_string.to_s == ""
    return original_hash
  end

  key, subkey = dot_separated_string.to_s.upcase.split(".", 2)
  subnode = get_subnode(key)

  if subnode.respond_to?(:get_value)
    return subnode.get_value(subkey)
  else
    return subnode.to_s
  end
end
to_hash() click to toggle source
# File lib/mhc/config.rb, line 101
def to_hash
  hash = {}
  syntax.keywords.each do |key|
    var = syntax.instance_variable_name(key)
    obj = instance_variable_get(var)
    obj = obj.respond_to?(:to_hash) ? obj.to_hash : obj.to_s
    hash[key] = obj
  end
  return hash
end
to_yaml() click to toggle source
# File lib/mhc/config.rb, line 97
def to_yaml
  return self.to_hash.to_yaml
end

Private Instance Methods

create_subnode(keyword, value) click to toggle source
# File lib/mhc/config.rb, line 122
def create_subnode(keyword, value)
  item_class = syntax.item_class(keyword)
  if item_class.is_a?(Array)
    return List.new(item_class.first, value)
  elsif item_class == String
    return value.to_s
  else
    return item_class.new(value)
  end
end
get_subnode(key) click to toggle source
# File lib/mhc/config.rb, line 117
def get_subnode(key)
  raise Mhc::ConfigurationError, "Invalid key: #{key}" unless syntax.keyword?(key)
  return instance_variable_get(syntax.instance_variable_name(key))
end
syntax() click to toggle source
# File lib/mhc/config.rb, line 113
def syntax
  self.class.syntax
end