Permalink
Browse files

Add support for dynamically-created and appended arrays

  • Loading branch information...
1 parent 046eba1 commit 7341db1187547d747791d14001262494915406a8 @mbklein mbklein committed Nov 14, 2011
Showing with 34 additions and 5 deletions.
  1. +16 −5 lib/confstruct/hash_with_struct_access.rb
  2. +18 −0 spec/confstruct/hash_with_struct_access_spec.rb
@@ -129,14 +129,25 @@ def lookup! key_path
end
def method_missing sym, *args, &block
- if args.length > 1
- super(sym,*args,&block)
- end
-
name = sym.to_s.chomp('=').to_sym
result = nil
- if args.length == 1
+
+ if name.to_s =~ /^add_(.+)!$/
+ name = $1.to_sym
+ self[name] = [] unless self.has_key?(name)
+ unless self[name].is_a?(Array)
+ raise TypeError, "Cannot #add! to a #{self[name].class}"
+ end
+ if args.length > 0
+ result = self[name].push *args
+ elsif block_given?
+ result = HashWithStructAccess.new(@@hash_class.new)
+ self[name].push result
+ end
+ elsif args.length == 1
result = self[name] = args[0]
+ elsif args.length > 1
+ super(sym,*args,&block)
else
result = self[name]
if result.nil? and block_given?
@@ -203,5 +203,23 @@
@hwsa.github.regproc.is_a?(Proc).should be_true
end
+ it "should create arrays on the fly" do
+ @hwsa.github do
+ add_roles!({:jeeves => :valet}, {:wooster => :dolt})
+ add_roles! do
+ psmith :chum
+ end
+ end
+ @hwsa.github.roles.should == [{:jeeves => :valet}, {:wooster => :dolt}, {:psmith => :chum}]
+ end
+
+ it "should not allow #add!ing to non-Array types" do
+ lambda {
+ @hwsa.github do
+ add_url! 'https://github.com/mbklein/busted'
+ end
+ }.should raise_error(TypeError)
+ end
+
end
end

0 comments on commit 7341db1

Please sign in to comment.