Class: A9n::Loader

Inherits:
Object
  • Object
show all
Defined in:
lib/a9n/loader.rb

Constant Summary collapse

COMMON_NAMESPACE =
'defaults'.freeze
KNOWN_NAMESPACES =
[COMMON_NAMESPACE, 'development', 'test', 'staging', 'production'].freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file_path, scope, env) ⇒ Loader

Returns a new instance of Loader.



8
9
10
11
12
13
# File 'lib/a9n/loader.rb', line 8

def initialize(file_path, scope, env)
  @scope = scope
  @env = ::A9n::StringInquirer.new(env.to_s)
  @local_file = file_path
  @example_file = "#{file_path}.example"
end

Instance Attribute Details

#envObject (readonly)

Returns the value of attribute env.



3
4
5
# File 'lib/a9n/loader.rb', line 3

def env
  @env
end

#example_fileObject (readonly)

Returns the value of attribute example_file.



3
4
5
# File 'lib/a9n/loader.rb', line 3

def example_file
  @example_file
end

#local_fileObject (readonly)

Returns the value of attribute local_file.



3
4
5
# File 'lib/a9n/loader.rb', line 3

def local_file
  @local_file
end

#scopeObject (readonly)

Returns the value of attribute scope.



3
4
5
# File 'lib/a9n/loader.rb', line 3

def scope
  @scope
end

#structObject (readonly)

Returns the value of attribute struct.



3
4
5
# File 'lib/a9n/loader.rb', line 3

def struct
  @struct
end

Class Method Details

.load_yml(file_path, scope, env) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/a9n/loader.rb', line 30

def load_yml(file_path, scope, env)
  return nil unless File.exist?(file_path)

  yml = A9n::YamlLoader.load(file_path)

  if no_known_namespaces?(yml)
    prepare_hash(yml, scope).freeze
  else
    common_namespace = prepare_hash(yml[COMMON_NAMESPACE], scope)
    env_namespace    = prepare_hash(yml[env], scope)

    A9n::Hash.merge(common_namespace, env_namespace).freeze
  end
end

.no_known_namespaces?(yml) ⇒ Boolean

Returns:

  • (Boolean)


51
52
53
# File 'lib/a9n/loader.rb', line 51

def no_known_namespaces?(yml)
  !yml.keys.intersect?(KNOWN_NAMESPACES)
end

.prepare_hash(data, scope) ⇒ Object



45
46
47
48
49
# File 'lib/a9n/loader.rb', line 45

def prepare_hash(data, scope)
  return nil unless data.is_a?(::Hash)

  A9n::Hash.deep_prepare(data, scope).freeze
end

Instance Method Details

#getObject



15
16
17
# File 'lib/a9n/loader.rb', line 15

def get
  struct || load
end

#loadObject



19
20
21
22
23
24
25
26
27
# File 'lib/a9n/loader.rb', line 19

def load
  local_config    = self.class.load_yml(local_file, scope, env)
  example_config  = self.class.load_yml(example_file, scope, env)

  ensure_data_presence!(local_config, example_config)
  ensure_keys_presence!(local_config, example_config)

  @struct = A9n::Struct.new(local_config || example_config)
end