Permalink
Browse files

Add HashWithStructAccess#has? and HashWithStructAccess#lookup!

  • Loading branch information...
1 parent b65b26d commit 4020c359d8f947b3e468cbe14cb49925693e8f69 @mbklein mbklein committed Nov 11, 2011
Showing with 40 additions and 2 deletions.
  1. +30 −2 lib/confstruct/hash_with_struct_access.rb
  2. +10 −0 spec/confstruct/hash_with_struct_access_spec.rb
@@ -91,6 +91,20 @@ def deferred! &block
Deferred.new(&block)
end
+ def has? key_path
+ val = self
+ keys = key_path.split(/\./)
+ keys.each do |key|
+ return false if val.nil?
+ if val.respond_to?(:has_key?) and val.has_key?(key.to_sym)
+ val = val[key.to_sym]
+ else
+ return false
+ end
+ end
+ return true
+ end
+
def inspect
r = self.keys.collect { |k| "#{k.inspect}=>#{self[k].inspect}" }
"{#{r.compact.join(', ')}}"
@@ -100,8 +114,18 @@ def is_a? klazz
klazz == @@hash_class or super
end
- def values
- keys.collect { |k| self[k] }
+ def lookup! key_path
+ val = self
+ keys = key_path.split(/\./)
+ keys.each do |key|
+ return nil if val.nil?
+ if val.respond_to?(:has_key?) and val.has_key?(key.to_sym)
+ val = val[key.to_sym]
+ else
+ return nil
+ end
+ end
+ return val
end
def method_missing sym, *args, &block
@@ -144,6 +168,10 @@ def symbolize key
self.class.symbolize(key)
end
+ def values
+ keys.collect { |k| self[k] }
+ end
+
protected
def do_deep_merge! source, target
source.each_pair do |k,v|
@@ -67,6 +67,16 @@
end
end
+ it "should properly respond to #has?" do
+ @hwsa.has?('github.url').should be_true
+ @hwsa.has?('github.foo.bar.baz').should be_false
+ end
+
+ it "should properly respond to #lookup!" do
+ @hwsa.lookup!('github.url').should == @hash[:github][:url]
+ @hwsa.lookup!('github.foo.bar.baz').should be_nil
+ end
+
it "should provide introspection" do
@hwsa.should_respond_to(:project)
@hash.keys.each do |m|

0 comments on commit 4020c35

Please sign in to comment.