Module: Configliere::ConfigFile

Defined in:
lib/configliere/config_file.rb

Overview

ConfigFile – load configuration from a simple YAML file

Instance Method Summary collapse

Instance Method Details

#read(filename, options = {}) ⇒ Configliere::Params

Load params from a YAML file, as a hash of handle => param_hash pairs

The env option is not coerced to_sym, so make sure your key type matches the file’s

Examples:

# Read from ~/.configliere/foo.yaml
Settings.read(foo.yaml)
# Read from config/foo.yaml and use settings appropriate for development/staging/production
Settings.read(App.root.join('config', 'environment.yaml'), :env => ENV['RACK_ENV'])

Parameters:

  • filename (String)

    the file to read. If it does not contain a ‘/’, the filename is expanded relative to Configliere::DEFAULT_CONFIG_DIR

  • options (Hash) (defaults to: {})

Options Hash (options):

  • :env (String)

    If an :env option is given, only the indicated subhash is merged. This lets you for example specify production / environment / test settings

Returns:

  • (Configliere::Params)

    the Settings object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/configliere/config_file.rb', line 29

def read filename, options={}
  if filename.is_a?(Symbol) then raise Configliere::DeprecatedError, "Loading from a default config file is no longer provided" ; end
  filename = expand_filename(filename)
  begin
    case filetype(filename)
    when 'json' then read_json(File.open(filename), options)
    when 'yaml' then read_yaml(File.open(filename), options)
    else            read_yaml(File.open(filename), options)
    end
  rescue Errno::ENOENT => e
    warn "Loading empty configliere settings file #{filename}"
  end
  self
end

#read_json(json_str, options = {}) ⇒ Object

we depend on you to require some sort of JSON



58
59
60
61
62
63
64
65
66
# File 'lib/configliere/config_file.rb', line 58

def read_json json_str, options={}
  new_data = JSON.load(json_str) || {}
  # Extract the :env (production/development/etc)
  if options[:env]
    new_data = new_data[options[:env]] || {}
  end
  deep_merge! new_data
  self
end

#read_yaml(yaml_str, options = {}) ⇒ Object



44
45
46
47
48
49
50
51
52
53
# File 'lib/configliere/config_file.rb', line 44

def read_yaml yaml_str, options={}
  require 'yaml'
  new_data = YAML.load(yaml_str) || {}
  # Extract the :env (production/development/etc)
  if options[:env]
    new_data = new_data[options[:env]] || {}
  end
  deep_merge! new_data
  self
end

#save!(filename) ⇒ Object

save to disk.

  • file is in YAML format, as a hash of handle => param_hash pairs

  • filename defaults to Configliere::DEFAULT_CONFIG_FILE (~/.configliere, probably)



71
72
73
74
75
76
# File 'lib/configliere/config_file.rb', line 71

def save! filename
  filename = expand_filename(filename)
  hsh = self.export.to_hash
  FileUtils.mkdir_p(File.dirname(filename))
  File.open(filename, 'w'){|f| f << YAML.dump(hsh) }
end