require 'yaml' module Sip class Config < Hash DBCONF_DEFAULT = { 'type' => 'mysql', 'host' => 'localhost', 'dbport' => nil } TABLECONF_DEFAULT = { 'incremental_index' => 'id', 'method' => 'append', 'incremental_index_value' => 0, 'partition_by' => nil, 'columns' => nil } def self.load_file(location) Config.new YAML.load_file(location) end def initialize(initial_values) # temp_keys are ones we'll delete before saving to a file @temp_keys = [] merge! initial_values # initialize defaults, including setting dbname and tablename ease of use keys self['databases'].each { |dbname, dbconf| self['databases'][dbname] = DBCONF_DEFAULT.merge(dbconf) self['databases'][dbname]['dbname'] = dbname self['databases'][dbname]['tables'].each { |tablename, tableconf| tableconf = {'hive_table_name' => "#{dbname}_#{tablename}"}.merge(TABLECONF_DEFAULT).merge(tableconf) self['databases'][dbname]['tables'][tablename] = tableconf self['databases'][dbname]['tables'][tablename]['tablename'] = tablename } } end def save_file(location) # remove unecessary dbname and tablename keys self['databases'].each { |dbname, dbconf| dbconf.delete 'dbname' dbconf['tables'].each { |tablename, tableconf| tableconf.delete 'tablename' } } File.open(location, 'w') { |f| h = Hash.new.merge self @temp_keys.each { |k| h.delete k } YAML.dump(h, f) } end def dbconf(dbname) self['databases'][dbname] end def tconf(dbname, tablename) dbconf(dbname)['tables'][tablename] end def store_database(dbname, conf) self['databases'][dbname] = conf end def store_table(dbname, tablename, conf) self['databases'][dbname]['tables'][tablename] = conf end def set_temp(other, keys) keys.each { |k| @temp_keys << k self[k] = other[k] } end end end