Class: SimpleConf::Loader

Inherits:
Struct
  • Object
show all
Defined in:
lib/simple-conf/loader.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#klassObject

Returns the value of attribute klass

Returns:

  • (Object)

    the current value of klass



6
7
8
# File 'lib/simple-conf/loader.rb', line 6

def klass
  @klass
end

Instance Method Details

#config_file_nameObject



40
41
42
43
44
# File 'lib/simple-conf/loader.rb', line 40

def config_file_name
  klass.respond_to?(:config_file_name) ?
    klass.config_file_name :
    "#{underscore(klass.name.split("::").last)}"
end

#load_file(path) ⇒ Object



21
22
23
24
25
# File 'lib/simple-conf/loader.rb', line 21

def load_file(path)
  yaml_file(path).each_pair do |key, value|
    set(key, value)
  end
end

#load_file_by_klass_env(path) ⇒ Object



27
28
29
30
31
# File 'lib/simple-conf/loader.rb', line 27

def load_file_by_klass_env(path)
  yaml_file(path).fetch(klass.env, {}).each_pair do |key, value|
    set(key, value)
  end if klass.respond_to?(:env)
end

#load_file_by_rails_env(path) ⇒ Object



15
16
17
18
19
# File 'lib/simple-conf/loader.rb', line 15

def load_file_by_rails_env(path)
  yaml_file(path).fetch(Rails.env, {}).each_pair do |key, value|
    set(key, value)
  end if rails_environment_defined?
end

#pathsObject



33
34
35
36
37
38
# File 'lib/simple-conf/loader.rb', line 33

def paths
  [
    "./config/#{config_file_name}.yml",
    "./config/#{config_file_name}.local.yml",
  ]
end

#runObject



7
8
9
10
11
12
13
# File 'lib/simple-conf/loader.rb', line 7

def run
  paths.each do |path|
    load_file(path)
    load_file_by_rails_env(path)
    load_file_by_klass_env(path)
  end
end

#underscore(camel_case_string) ⇒ Object



46
47
48
49
50
51
52
# File 'lib/simple-conf/loader.rb', line 46

def underscore(camel_case_string)
  camel_case_string.gsub(/::/, '/').
  gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
  gsub(/([a-z\d])([A-Z])/,'\1_\2').
  tr("-", "_").
  downcase
end

#yaml_file(path) ⇒ Object



54
55
56
57
58
# File 'lib/simple-conf/loader.rb', line 54

def yaml_file(path)
  return {} unless File.exists?(path)
  content = File.open(path).read
  YAML.load(ERB.new(content).result)
end