Class: KY::Configuration

Inherits:
Object
  • Object
show all
Defined in:
lib/ky/configuration.rb

Constant Summary collapse

AmbiguousEnvironmentFile =
Class.new(StandardError)

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}) ⇒ Configuration

Returns a new instance of Configuration.



6
7
8
9
# File 'lib/ky/configuration.rb', line 6

def initialize(opts={})
  @opts = opts
  @configuration = build_configuration
end

Instance Attribute Details

#configurationObject (readonly)

Returns the value of attribute configuration.



4
5
6
# File 'lib/ky/configuration.rb', line 4

def configuration
  @configuration
end

#optsObject (readonly)

Returns the value of attribute opts.



4
5
6
# File 'lib/ky/configuration.rb', line 4

def opts
  @opts
end

Instance Method Details

#[](key) ⇒ Object



11
12
13
# File 'lib/ky/configuration.rb', line 11

def [](key)
  configuration[key]
end

#build_configurationObject



19
20
21
22
23
24
25
26
27
28
# File 'lib/ky/configuration.rb', line 19

def build_configuration
  config = if ky_config_path = opts[:ky_config_path]
    YAML.load(File.read(ky_config_path)).with_indifferent_access
  elsif config_file_location
    YAML.load(File.read(config_file_location)).with_indifferent_access
  else
    DEFAULT_CONFIG
  end
  config.merge(current_environment_hash(config))
end

#config_file_locationObject



48
49
50
# File 'lib/ky/configuration.rb', line 48

def config_file_location
  (CONFIG_LOCATIONS * CONFIG_FILE_NAMES.count).zip(CONFIG_FILE_NAMES).map(&:join).find {|path| File.exist?(path) && !File.directory?(path) }
end

#current_environment_hash(partial_config) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/ky/configuration.rb', line 30

def current_environment_hash(partial_config)
  current_config = partial_config || configuration
  current_environment = opts[:environment] || current_config[:environment]
  env_file_paths = environment_files(current_config).select {|file| file.match(current_environment) if current_environment }
  if env_file_paths.count <= 1 # workaround for current possible env/path ambiguity
    env_file_path = env_file_paths.first
  else
    raise AmbiguousEnvironmentFile.new("More than one file path matched the environment")
  end
  hsh = env_file_path ?  YAML.load(File.read(env_file_path)).with_indifferent_access : {}
  (hsh[:configuration] ? hsh[:configuration].merge(opts) : hsh.merge(opts)).with_indifferent_access
end

#environment_files(partial_config) ⇒ Object



43
44
45
46
# File 'lib/ky/configuration.rb', line 43

def environment_files(partial_config)
  environments = (partial_config || configuration)[:environments].flat_map {|env| ["#{env}.yml", "#{env}.yaml"]}
  (CONFIG_LOCATIONS * environments.count).zip(environments).map(&:join).select {|path| File.exist?(path) && !File.directory?(path) }
end

#keysObject



15
16
17
# File 'lib/ky/configuration.rb', line 15

def keys
  configuration.keys
end