Class: Tarot::Config

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(files, env) ⇒ Config

Returns a new instance of Config.



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/tarot.rb', line 7

def initialize(files, env)
  @config_files = files
  @config_files = [@config_files] if @config_files.is_a? String
  @yaml = {}
  @raw_yaml = "---\n" + @config_files.map do |file|
    File.open(file).read.untaint.gsub(/^---.*$/, '')
  end.join("\n")
  @yaml = YAML::load(@raw_yaml).stringify_keys!
  #@config_files.each do |file|
  #  yaml = YAML::load(open(file).read).stringify_keys!
  #  recursive_merge(@yaml, yaml)
  #end
  add_mm @yaml
  @config_cache = {}
  @env = env
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args) ⇒ Object (private)



70
71
72
# File 'lib/tarot.rb', line 70

def method_missing(method, *args)
  @yaml[args[1] || @env].send method, *args
end

Instance Attribute Details

#config_filesObject

Returns the value of attribute config_files.



6
7
8
# File 'lib/tarot.rb', line 6

def config_files
  @config_files
end

#envObject

Returns the value of attribute env.



6
7
8
# File 'lib/tarot.rb', line 6

def env
  @env
end

#yamlObject

Returns the value of attribute yaml.



6
7
8
# File 'lib/tarot.rb', line 6

def yaml
  @yaml
end

Instance Method Details

#get(key, default = nil, env = @env) ⇒ Object



24
25
26
27
# File 'lib/tarot.rb', line 24

def get(key, default = nil, env = @env)
  @config_cache[env] ||= {}
  @config_cache[env][key] ||= key.split('.').inject(@yaml[env || @env]) {|e, part| e.try(:[], part) } || default
end

#merge(hash, namespace = nil) ⇒ Object



29
30
31
32
33
34
# File 'lib/tarot.rb', line 29

def merge(hash, namespace = nil)
  target = namespace.nil? ? @yaml[@env] : get(namespace)
  add_mm hash
  recursive_merge(target, hash)
  @config_cache.clear
end

#merge_file(file, namespace = nil) ⇒ Object



36
37
38
# File 'lib/tarot.rb', line 36

def merge_file(file, namespace = nil)
  merge YAML::load(open(file).read).stringify_keys!, namespace
end

#with_environment(env) ⇒ Object



40
41
42
43
44
45
46
# File 'lib/tarot.rb', line 40

def with_environment(env)
  env ||= self.env
  old_env, self.env = self.env, env
  result = yield if block_given?
  self.env = old_env
  result
end