Class: Settei::Loaders::SimpleLoader
- Inherits:
-
Object
- Object
- Settei::Loaders::SimpleLoader
- 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
-
#env_name ⇒ Object
readonly
Returns the value of attribute env_name.
Instance Method Summary collapse
-
#as_env_assignment ⇒ String
Convenience method for outputting "NAME=VALUE" in one call.
-
#as_env_value ⇒ String
Serialized config hash, for passing as environment variable.
- #as_hash ⇒ Hash
-
#initialize(dir: nil, env_name: 'APP_CONFIG') ⇒ SimpleLoader
constructor
A new instance of SimpleLoader.
-
#load(environment = nil) ⇒ self
Loads yaml file into memory.
Constructor Details
#initialize(dir: nil, env_name: 'APP_CONFIG') ⇒ SimpleLoader
Returns a new instance of 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_name ⇒ Object (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_assignment ⇒ String
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_value ⇒ String
Returns 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_hash ⇒ 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.
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 |