Module: Ditty::Services::Settings

Defined in:
lib/ditty/services/settings.rb

Overview

This is the central settings service Ditty. It is used to get the settings for various aspects of Ditty, and can also be used to configure your own application.

It has the concept of sections which can either be included in the main settings.yml file, or as separate files in the ‘config` folder. The values in separate files will be used in preference of those in the `settings.yml` file.

Constant Summary collapse

CONFIG_FOLDER =
'./config'
CONFIG_FILE =
"#{CONFIG_FOLDER}/settings.yml"

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.values(scope = :settings) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/ditty/services/settings.rb', line 35

def values(scope = :settings)
  @values ||= begin
    v = Hash.new do |h, k|
      h[k] = if File.file?("#{CONFIG_FOLDER}/#{k}.yml")
        read("#{CONFIG_FOLDER}/#{k}.yml")
      elsif k != :settings && h[:settings].key?(k)
        h[:settings][k]
      end
      h[k]
    end
    v[:settings] = File.file?(CONFIG_FILE) ? read(CONFIG_FILE) : {}
    v
  end
  @values[scope]
end

Class Method Details

.[](key) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
# File 'lib/ditty/services/settings.rb', line 23

def [](key)
  keys = key.to_s.split('.').map(&:to_sym)
  from = values
  if keys.count > 1 && scope?(keys.first)
    from = values(keys.first)
    keys = keys[1..]
    key = keys.join('.')
  end
  key = key.to_sym if key.respond_to?(:to_sym)
  from[key] || from.dig(*keys)
end

.read(filename) ⇒ Object



57
58
59
60
61
# File 'lib/ditty/services/settings.rb', line 57

def read(filename)
  base = YAML.safe_load(ERB.new(File.read(filename)).result).deep_symbolize_keys
  base.deep_merge!(base[ENV['APP_ENV'].to_sym]) unless ENV['APP_ENV'].nil? || base[ENV['APP_ENV'].to_sym].nil?
  base
end

.scope?(name) ⇒ Boolean

Returns:

  • (Boolean)


51
52
53
# File 'lib/ditty/services/settings.rb', line 51

def scope?(name)
  @values.key?(name.to_sym) || File.file?("#{CONFIG_FOLDER}/#{name}.yml")
end