Permalink
Browse files

Refactored to use my latest ClostedStruct.

  • Loading branch information...
1 parent eefb431 commit 8e3584f824cb41a5e4052f4ca23fd89b8b425d03 @cjbottaro committed Aug 27, 2009
Showing with 27 additions and 22 deletions.
  1. +1 −17 lib/app_config.rb
  2. +26 −5 lib/closed_struct.rb
View
@@ -22,7 +22,7 @@ def reload!
conf1 = load_conf_file(@conf_path_1)
conf2 = load_conf_file(@conf_path_2)
conf = recursive_merge(conf1, conf2)
- @config = convert(conf)
+ @config = ClosedStruct.r_new(conf)
end
private
@@ -42,22 +42,6 @@ def load_conf_file(conf_path)
end
end
- # Recursively converts Hashes to ClosedStructs (including Hashes inside Arrays)
- def convert(h) #:nodoc:
- s = ClosedStruct.new(h.keys)
- h.each do |k, v|
- if v.instance_of?(Hash)
- s.send( (k+'=').to_sym, convert(v))
- elsif v.instance_of?(Array)
- converted_array = v.collect { |e| e.instance_of?(Hash) ? convert(e) : e }
- s.send( (k+'=').to_sym, converted_array)
- else
- s.send( (k+'=').to_sym, v)
- end
- end
- s
- end
-
# Recursively merges hashes. h2 will overwrite h1.
def recursive_merge(h1, h2) #:nodoc:
h1.merge(h2){ |k, v1, v2| v2.kind_of?(Hash) ? recursive_merge(v1, v2) : v2 }
View
@@ -1,13 +1,22 @@
require 'ostruct'
-class ClosedStruct < OpenStruct # :nodoc:
+# Like OpenStruct, but raises an exception if you try to access a member that wasn't specified in the initializer.
+class ClosedStruct < OpenStruct
+
+ def self.r_new(hash)
+ closed_struct = ClosedStruct.new(hash)
+ closed_struct.send(:recursive_initialize)
+ closed_struct
+ end
def initialize(*args)
- if args.length == 1
+ if args.length == 1 and args.first.kind_of?(Hash)
super(args.first)
+ elsif args.length > 1 and args.all?{ |arg| [Symbol, String].include?(arg.class) }
+ args = args.inject({}){ |memo, arg| memo[arg.to_sym] = nil; memo }
+ super(args)
else
- h = args.inject({}){ |memo, k| memo[k] = nil; memo }
- super(h)
+ raise ArgumentError, "invalid arguments: #{args.inspect}"
end
@closed = true
end
@@ -36,4 +45,16 @@ def to_h
@table.dup
end
-end
+private
+
+ def recursive_initialize
+ @table.each do |k, v|
+ if v.kind_of?(Hash)
+ @table[k] = ClosedStruct.r_new(v)
+ elsif v.kind_of?(Array)
+ @table[k] = v.collect{ |e| e.kind_of?(Hash) ? ClosedStruct.r_new(e) : e }
+ end
+ end
+ end
+
+end

0 comments on commit 8e3584f

Please sign in to comment.