Skip to content

Commit

Permalink
Add HashWithStructAccess#has? and HashWithStructAccess#lookup!
Browse files Browse the repository at this point in the history
  • Loading branch information
mbklein committed Nov 11, 2011
1 parent b65b26d commit 4020c35
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 2 deletions.
32 changes: 30 additions & 2 deletions lib/confstruct/hash_with_struct_access.rb
Expand Up @@ -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(', ')}}"
Expand All @@ -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
Expand Down Expand Up @@ -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|
Expand Down
10 changes: 10 additions & 0 deletions spec/confstruct/hash_with_struct_access_spec.rb
Expand Up @@ -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|
Expand Down

0 comments on commit 4020c35

Please sign in to comment.