Sha256: b340bf7782158ed94511a0e91b46001f1c87c2452ad56b9fb7078a6eb3e9a543

Contents?: true

Size: 1.34 KB

Versions: 1

Compression:

Stored size: 1.34 KB

Contents

require 'yaml'
require 'hash'
require 'errors'
require 'configuration_block'

module Configr
  class Configuration
    attr_accessor :base, :attributes, :yaml
    
    def initialize(yaml=nil)
      self.base = ConfigurationBlock.new
      self.yaml = yaml
    end
    
    def self.configure(yaml=nil)
      instance = self.new(yaml)
      
      yield instance.base if block_given?
      
      instance.attributes = instance.base.attributes
      
      instance.merge_configurations!
      
      instance.attributes.recursive_normalize!
      
      instance
    end
    
    def [](value)
      self.attributes[value]
    end
    
    def method_missing(method, *args, &block)
      name = method.to_s
      
      case
      when name.include?("=")
        raise ConfigurationLocked, "Blocked from configuring values after configuration has been run."
      when name.include?("?")
        !self.attributes[name.gsub("?", "").to_sym].nil?
      else
        self.attributes[method.to_sym] or self.attributes[method.to_s]
      end
    end
    
    def merge_configurations!
      return unless self.yaml
      
      hash = if File.exists?(self.yaml)
        YAML.load_file(self.yaml)
      else
        YAML.load(self.yaml)
      end
      
      hash = Hash.new(hash)
      hash.recursive_symbolize_keys!
      
      self.attributes.merge!(hash)
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
configr-0.2.0 lib/configr/configuration.rb