Module: Junkie::Config

Overview

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

Examples:

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

Class Method Summary collapse

Class Method Details

.collect_default_configsHash

Collects the DEFAULT_CONFIG from all including Classes

Returns:

  • (Hash)

    hash of hashes indexed by class name



62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/junkie/config.rb', line 62

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

.get_config(source) ⇒ Hash

Get the config hash for the calling module merged with the hash from the config file

Parameters:

  • should (Class)

    be equal to ‘self`

Returns:

  • (Hash)

    merged version of DEFAULT_CONFIG from the calling class



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/junkie/config.rb', line 40

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

  class_name = source.class.to_s
  (class_name = source.to_s) if source.is_a? Class

  return @comlete_config[class_name]
end

.included(mod) ⇒ Object

Callback method which is called when a class includes the module

Parameters:

  • the (Class)

    class which includes the module



30
31
32
# File 'lib/junkie/config.rb', line 30

def self.included(mod)
  @including_classes << mod
end