Skip to content

Commit

Permalink
Apply symbol-string key conversion to BSON::Document#dig too.
Browse files Browse the repository at this point in the history
  • Loading branch information
stulentsev committed Dec 5, 2017
1 parent 6322003 commit 97c236c
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 1 deletion.
20 changes: 20 additions & 0 deletions lib/bson/document.rb
Expand Up @@ -172,6 +172,26 @@ def merge!(other)

alias :update :merge!

if instance_methods.include?(:dig)
# Retrieves the value object corresponding to the each key objects repeatedly.
# Will normalize symbol keys into strings.
#
# @example Get value from nested sub-documents, handling missing levels.
# document # => { :key1 => { "key2" => "value"}}
# document.dig(:key1, :key2) # => "value"
# document.dig("key1", "key2") # => "value"
# document.dig("foo", "key2") # => nil
#
# @param [ Array<String, Symbol> ] *keys Keys, which constitute a "path" to the nested value.
#
# @return [ Object, NilClass ] The requested value or nil.
#
# @since 3.0.0
def dig(*keys)
super(*keys.map{|key| convert_key(key)})
end
end

private

def convert_key(key)
Expand Down
24 changes: 23 additions & 1 deletion spec/bson/document_spec.rb
Expand Up @@ -96,6 +96,28 @@
end
end

if described_class.instance_methods.include?(:dig)
describe "#dig" do
let(:document) do
described_class.new("key1" => { :key2 => "value" })
end

context "when provided string keys" do

it "returns the value" do
expect(document.dig("key1", "key2")).to eq("value")
end
end

context "when provided symbol keys" do

it "returns the value" do
expect(document.dig(:key1, :key2)).to eq("value")
end
end
end
end

describe "#delete" do

shared_examples_for "a document with deletable pairs" do
Expand Down Expand Up @@ -766,7 +788,7 @@
"#{35.to_bson}"+
"#{BSON::Document::BSON_TYPE}0#{BSON::NULL_BYTE}#{12.to_bson}#{BSON::Int32::BSON_TYPE}a#{BSON::NULL_BYTE}#{1.to_bson}#{BSON::NULL_BYTE}" +
"#{BSON::Document::BSON_TYPE}1#{BSON::NULL_BYTE}#{12.to_bson}#{BSON::Int32::BSON_TYPE}b#{BSON::NULL_BYTE}#{2.to_bson}#{BSON::NULL_BYTE}" +
"#{BSON::NULL_BYTE}" +
"#{BSON::NULL_BYTE}" +
"#{BSON::NULL_BYTE}"
end

Expand Down

0 comments on commit 97c236c

Please sign in to comment.