Class: KonfigYaml

Inherits:
Object
  • Object
show all
Includes:
NeoHash::Support
Defined in:
lib/konfig_yaml/main.rb,
lib/konfig_yaml/version.rb

Overview

KonfigYaml main class

Constant Summary collapse

VERSION =
'1.0.0'

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name = 'app', opts = nil) ⇒ KonfigYaml

Create an configuration from YAML file

Parameters:

  • name (String) (defaults to: 'app')

    (‘app’) the basename of YAML file

  • opts (Hash) (defaults to: nil)

    the options to intialize

Options Hash (opts):

  • :env (String) — default: ENV['RUBY_ENV'] || ENV['RAILS_ENV'] || ENV['RACK_ENV'] || 'development'

    execution environment

  • :erb (Boolean) — default: false

    whether evaluate ERB or not

  • :path (String) — default: 'config'

    directory path that contains the YAML file



16
17
18
19
20
21
22
23
24
25
26
# File 'lib/konfig_yaml/main.rb', line 16

def initialize(name = 'app', opts = nil)
  if name.is_a?(Hash) && opts.nil?
    opts = name
    name = 'app'
  elsif opts.nil?
    opts = {}
  end

  hash = self.class.create_hash(name, opts)
  set_inner_hash(hash)
end

Class Method Details

.create_hash(name, opts) ⇒ Object



60
61
62
63
64
65
66
67
68
# File 'lib/konfig_yaml/main.rb', line 60

def create_hash(name, opts)
  name ||= 'app'
  path = File.expand_path(opts[:path] || 'config', Dir.pwd)
  env = environment(opts)
  expand_erb = opts.fetch(:erb, false)

  h = load_config(name, env, path, expand_erb)
  dup_hash_expand_envs(h)
end

.setup {|config| ... } ⇒ Object

Setup global configuration class from YAML file If this is called without block, this defines ‘Settings` class by loading `config/app.yml`

Yields:

  • (config)

    configuration to the block

Yield Parameters:

  • config (OpenStruct)

    support ‘const_name`, `name`, `env`, `path` and `use_cahe` attribute



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/konfig_yaml/main.rb', line 33

def setup(&block)
  const_name = 'Settings'
  name = nil
  opts = {}

  if block_given?
    cfg = OpenStruct.new
    yield(cfg)
    cfg.each_pair do |key, val|
      if key == :const_name
        const_name = val
      elsif key == :name
        name = val
      else
        opts[key] = val
      end
    end
  end

  hash = create_hash(name, opts)
  cls = Class.new do
    extend NeoHash::Support
    set_inner_hash(hash)
  end
  Object.const_set(const_name, cls)
end