Class: Settei::Loaders::SimpleLoader

Inherits:
Object
  • Object
show all
Defined in:
lib/settei/loaders/simple_loader.rb

Overview

Loader designed to load hash from environment variable and YAML files. After initialization, call #load to load hash into memory, then call #as_hash, #as_env_value, or #as_env_assignment to obtain the results. e.g. loader.load(:production).as_hash

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(dir: nil, env_name: 'APP_CONFIG') ⇒ SimpleLoader

Returns a new instance of SimpleLoader

Parameters:

  • dir (String)

    path of directory containing config YAML files

  • env_name (String)

    name for environment variable


16
17
18
19
# File 'lib/settei/loaders/simple_loader.rb', line 16

def initialize(dir: nil, env_name: 'APP_CONFIG')
  @dir = dir
  @env_name = env_name
end

Instance Attribute Details

#env_nameObject (readonly)

Returns the value of attribute env_name


12
13
14
# File 'lib/settei/loaders/simple_loader.rb', line 12

def env_name
  @env_name
end

Instance Method Details

#as_env_assignmentString

Convenience method for outputting "NAME=VALUE" in one call.

Returns:


70
71
72
73
74
# File 'lib/settei/loaders/simple_loader.rb', line 70

def as_env_assignment
  ensure_loaded!

  "#{@env_name}=#{as_env_value}"
end

#as_env_valueString

Returns serialized config hash, for passing as environment variable

Returns:

  • (String)

    serialized config hash, for passing as environment variable


60
61
62
63
64
65
66
# File 'lib/settei/loaders/simple_loader.rb', line 60

def as_env_value
  ensure_loaded!

  Base64.strict_encode64(
    Zlib::Deflate.deflate(@yaml)
  )
end

#as_hashHash

Returns:

  • (Hash)

53
54
55
56
57
# File 'lib/settei/loaders/simple_loader.rb', line 53

def as_hash
  ensure_loaded!

  YAML.load(@yaml)
end

#load(environment = nil) ⇒ self

Loads yaml file into memory. If ENV[@env_name] exists, loader loads from it, otherwise load from YAML file.

YAML file is picked based on provided environment. If environment is not specified, or specified environment file does not exist, default.yml is loaded.

Parameters:

  • environment (String) (defaults to: nil)

    application environment (e.g. production/test)

Returns:

  • (self)

    for further chaining


32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/settei/loaders/simple_loader.rb', line 32

def load(environment = nil)
  if !ENV[@env_name].nil?
    @yaml = Zlib::Inflate.inflate(
      Base64.strict_decode64(ENV[@env_name])
    )
  else
    if environment
      env_specific_file_path = "#{@dir}/#{environment}.yml"
      if File.exist?(env_specific_file_path)
        file_path = env_specific_file_path
      end
    end
    file_path ||= "#{@dir}/default.yml"

    @yaml = open(file_path).read
  end

  self
end