Report abuse

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# Parses config/site.yml and creates an OpenStruct-like Site configuration object.
# The site.yml file can use ERB, just like fixture yml files.
# The file is expected to have a top-level key for the current Rails environment.
# Its values become attribute on the Site object.
# Values that have sub-keys become nested objects.
#
# For example, a site.yml file containing
#
#  development:
#    password: sesame
#    flickr:
#      api_key: <%= "ali" * 2 %>
#    hot_or_not:
#      api_key: baba
#
# creates a Site object that can be used like
#
#   Site.password  # => "sesame"
#   Site.name = "Test"
#   Site.name  # => "Test"
#   Site::Flickr.api_key  # => "aliali"
#   Site::HotOrNot.api_key  # => "baba"

require 'ostruct'

module OpenModule
  def method_missing(*args)
    @ostruct ||= OpenStruct.new
    @ostruct.send(*args)
  end
  
  def self.build_constant_from_hash(constant_name, hash, parent = Object)
    parent.const_set(constant_name.classify, Module.new)
    constant = parent.const_get(constant_name.classify)
    constant.extend(self)

    hash.each do |key, value|
      if value.is_a?(Hash)
        build_constant_from_hash(key, value, constant)
      else
        constant.send("#{key}=", value)
      end
    end
  end
end

raw_config = File.read("#{Rails.root}/config/site.yml")
erb_config = ERB.new(raw_config).result
config = YAML.load(erb_config)[Rails.env]

OpenModule.build_constant_from_hash('Site', config)