Sha256: b163fe7f9a2955d4a29d10f0998ac6d934ef98b182c4f9eb66c1deb2c5ab5e6f

Contents?: true

Size: 1.58 KB

Versions: 3

Compression:

Stored size: 1.58 KB

Contents

require 'ostruct'
module RailsConfig
  class Options < OpenStruct

    def empty?
      marshal_dump.empty?
    end

    def add_source!(source)
      # handle yaml file paths
      source = (Sources::YAMLSource.new(source)) if source.is_a?(String)

      @config_sources ||= []
      @config_sources << source
    end

    # look through all our sources and rebuild the configuration
    def reload!
      conf = {}
      @config_sources.each do |source|
        source_conf = source.load

        if conf.empty?
          conf = source_conf
        else
          DeepMerge.deep_merge!(source_conf, conf, :preserve_unmergeables => false)
        end
      end

      # swap out the contents of the OStruct with a hash (need to recursively convert)
      marshal_load(__convert(conf).marshal_dump)

      return self
    end

    alias :load! :reload!

    def reload_from_files(*files)
      RailsConfig.load_and_set_settings(files)
      reload!
    end

    protected

    # Recursively converts Hashes to Options (including Hashes inside Arrays)
    def __convert(h) #:nodoc:
      s = self.class.new

      h.each do |k, v|
        s.new_ostruct_member(k)
        if v.is_a?(Hash)
          if(v["type"] == "hash")
            val = v["contents"]
          else
            val = __convert(v)
          end
          s.send( (k+'=').to_sym, val)
        elsif v.is_a?(Array)
          converted_array = v.collect { |e| e.instance_of?(Hash) ? __convert(e) : e }
          s.send("#{k}=".to_sym, converted_array)
        else
          s.send("#{k}=".to_sym, v)
        end
      end
      s
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
rails_config-0.2.0 lib/rails_config/options.rb
rails_config-0.1.8 lib/rails_config/options.rb
rails_config-0.1.7 lib/rails_config/options.rb