require 'hashconfig' require 'fileutils' module Junkie # Module that encapsulates the handling for configuration into a module # which can be included into any Class which includes a constant Hash named # DEFAULT_CONFIG is returned by Config.get_config(self) merged with the # version from the config file # # @example # class Foo # include Config # # DEFAULT_CONFIG = { refresh: 5 } # # def initialize # # the following holds the merged version from DEFAULT_CONFIG # @config = Config.get_config(self) # end # end # module Config @including_classes = [] @comlete_config = nil # Callback method which is called when a class includes the module # # @param [Class] the class which includes the module def self.included(mod) @including_classes << mod end # Get the config hash for the calling module merged with the hash from the # config file # # @param [Class] should be equal to `self` # @return [Hash] merged version of DEFAULT_CONFIG from the calling class def self.get_config(source) # builds up the complete config and merges them with serialzed version # at the first call to this method if @comlete_config.nil? default_config = self.collect_default_configs FileUtils.mkdir_p File.dirname(Junkie::CONFIG_FILE) @comlete_config = default_config.merge_with_serialized(Junkie::CONFIG_FILE) end return @comlete_config[source.class.to_s] end # Collects the DEFAULT_CONFIG from all including Classes # # @return [Hash] hash of hashes indexed by class name def self.collect_default_configs config = Hash.new @including_classes.each do |klass| if not klass.const_defined? :DEFAULT_CONFIG raise NotImplementedError, "#{klass} has to include a constant DEFAULT_CONFIG as Hash" end config[klass.to_s] = klass.const_get :DEFAULT_CONFIG end config end end end