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


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.


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


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


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.


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