Sha256: b2068c2ab587d104e939ff6081b8c995a277f142443d7bda35372bde0f73c870

Contents?: true

Size: 1.7 KB

Versions: 1

Compression:

Stored size: 1.7 KB

Contents

require 'ostruct'
require 'socket'
require 'active_support/core_ext/hash'

module HostConfig
  VERSION = "0.0.3"

  class MissingConfigFile < StandardError; end

  class << self
    def init!( opts={} )
      @base_path = opts[:base_path] || Rails.root
      @logger = opts[:logger] || Rails.logger
      @hostname = opts[:hostname] || Socket.gethostname.split('.').shift
      @config = {}
      @config[:hostname] = opts[:hostname]
      @logger.debug "Loading host config #{@hostname}"
      process( load_config( @hostname ) )
    end

    private

    def load_config( file )
      begin
        path = File.join( @base_path, 'config', 'hosts', "#{file}.yml" )
        data = File.read(path)
        YAML.load( data )
      rescue Errno::ENOENT
        raise MissingConfigFile.new( "Missing config file '#{path}', could not setup HostConfig!" )
      end
    end

    def process( config )
      load_before = config.delete('load_before')
      load_after = config.delete('load_after')

      if load_before.is_a? Array
        load_before.each do |file|
          @logger.debug "   including... _#{file}"
          c = load_config( "_#{file}" )
          process( c )
        end
      end

      @config.deep_merge! config

      if load_after.is_a? Array
        load_after.each do |file|
          c = load_config( "_#{file}" )
          process( c )
        end
      end

      to_openstruct(@config)
    end

    def to_openstruct( obj )
      case obj
      when Array
        obj.map { |el| to_openstruct(el) }
      when Hash
        ::OpenStruct.new( obj.each_with_object({}) do |(k,v), h|
                            h[k] = to_openstruct(v)
                          end )
      else
        obj
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
host_config-0.0.3 lib/host_config.rb