Class: EasyConfRails

Inherits:
Rails::Railtie
  • Object
show all
Defined in:
lib/easyconf-rails.rb

Defined Under Namespace

Classes: EasyConfError, InvalidConfig, InvalidDefaults, NonexistentConfig

Instance Method Summary collapse

Instance Method Details

#assign_configObject

Assign $config to the result of load_config().



157
158
159
160
161
# File 'lib/easyconf-rails.rb', line 157

def assign_config()
	$config = load_config()
	$config.define_singleton_method(:reload!, &method(:assign_config))
	$config
end

#hash_to_openstruct(hash) ⇒ Object

Turn a Hash or Array and all of its Hash children into OpenStructs.



94
95
96
97
98
99
100
101
102
# File 'lib/easyconf-rails.rb', line 94

def hash_to_openstruct(hash)
	(hash.is_a?(Hash) ? hash.keys : (0...hash.length)).each do |key|
		if hash[key].is_a?(Hash) or hash[key].is_a?(Array)
			hash[key] = hash_to_openstruct(hash[key])
		end
	end

	hash.is_a?(Array) ? hash : SemiOpenStruct.new(hash)
end

#load_configObject

Load the configuration file at Rails.root/config.yml and the defaults file at Rails.root/config/defaults.yml.



130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
# File 'lib/easyconf-rails.rb', line 130

def load_config()
	config_location = Rails.root + 'config.yml'
	if File.exists?(config_location)
		begin
			config_hash = YAML.load_file(config_location)
		rescue Psych::SyntaxError => ex
			raise InvalidConfig.new(ex.line, ex.column)
		end
	else
		raise(NonexistentConfig)
	end

	defaults_location = Rails.root + 'config' + 'defaults.yml'
	if File.exists?(defaults_location)
		begin
			defaults_hash = YAML.load_file(defaults_location)
		rescue Psych::SyntaxError => ex
			raise InvalidDefaults.new(ex.line, ex.column)
		end
	else
		defaults_hash = {}
	end

	hash_to_openstruct(merge_hashes(config_hash, defaults_hash))
end

#merge_hashes(*hashes) ⇒ Object

Merge two hashes recursively, with precedence going to the earliest Hash with that value defined. For example, merge_hashes( {b: 1, c: 2}, {d: 3, c: 4} ) will return {b: 1, d: 3, c: 2}



109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
# File 'lib/easyconf-rails.rb', line 109

def merge_hashes(*hashes)
	merged = {}

	hashes.each do |hash|
		hash.each do |key, val|
			if merged.has_key?(key) and merged[key].is_a?(Hash) and val.is_a?(Hash)
				merged[key] = merge_hashes(merged[key], val)
			elsif not merged.has_key?(key)
				merged[key] = val
			else
				# merged[key] and val are not both Hashes, and therefore can't be
				# merged. merged[key] takes precedence over val, and we do nothing.
			end
		end
	end

	merged
end