Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Add support for dynamically-created and appended arrays

  • Loading branch information...
commit 7341db1187547d747791d14001262494915406a8 1 parent 046eba1
@mbklein mbklein authored
View
21 lib/confstruct/hash_with_struct_access.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?
View
18 spec/confstruct/hash_with_struct_access_spec.rb
@@ -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
Please sign in to comment.
Something went wrong with that request. Please try again.