Class: Jobim::Settings

Inherits:
Object
  • Object
show all
Defined in:
lib/jobim/settings.rb

Overview

Manages applications settings and configuration. Handles sane defaults and the loading / merging of configuration from files.

Constant Summary collapse

VALID_KEYS =
[:daemonize, :dir, :host, :port, :prefix, :quiet, :conf_dir]

Instance Method Summary collapse

Constructor Details

#initialize(defaults = {}) ⇒ Settings

Returns a new instance of Settings.



10
11
12
13
# File 'lib/jobim/settings.rb', line 10

def initialize(defaults = {})
  update(defaults)
  load if conf_dir
end

Instance Method Details

#load(dir = conf_dir) ⇒ Jobim::Settings

Loads all configuration files from provided directory up. Defaults to the current working directory of the program.

Parameters:

  • directory (String)

    to load files from (defaults to Dir.pwd)

Returns:



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/jobim/settings.rb', line 48

def load(dir = conf_dir)
  dir = Pathname(File.expand_path(dir))
  files = []

  loop do
    file = File.expand_path('.jobim.yml', dir)
    if File.exists? file
      files.unshift(file)
    else
      file = File.expand_path('.jobim.yaml', dir)
      files.unshift(file) if File.exists? file
    end

    break if dir.root?

    dir = dir.parent
  end

  files.each { |file| load_file(file) }

  self
end

#load_file(file) ⇒ Jobim::Settings

Loads a configuration file in the yaml format into the settings object.

Parameters:

  • file (String)

    path to the configuration file

Returns:



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/jobim/settings.rb', line 24

def load_file(file)
  opts = YAML.load_file(file) || {}
  opts.keys.each do |key|
    begin
      opts[key.to_s.downcase.to_sym || key] = opts.delete(key)
    rescue
      opts[key] = opts.delete(key)
    end
  end

  if opts[:dir]
    unless Pathname.new(opts[:dir]).absolute?
      opts[:dir] = File.expand_path("../#{opts[:dir]}", file)
    end
  end

  update(opts)
end

#update(opts) ⇒ Object



15
16
17
18
# File 'lib/jobim/settings.rb', line 15

def update(opts)
  VALID_KEYS.each { |key| send("#{key}=", opts[key]) unless opts[key].nil? }
  self
end