mongo-parser-rb 0.0.3 → 0.0.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- data/lib/mongo-parser-rb/field.rb +15 -2
- data/lib/mongo-parser-rb/version.rb +1 -1
- data/test/mongo-parser-rb/field_test.rb +14 -0
- metadata +1 -1
@@ -9,7 +9,12 @@ module MongoParserRB
|
|
9
9
|
def value_in_document(document)
|
10
10
|
document = stringify_keys(document)
|
11
11
|
@field_parts.reduce(document) do |value, field|
|
12
|
-
value
|
12
|
+
case value
|
13
|
+
when Array
|
14
|
+
value[field.to_i]
|
15
|
+
when Hash
|
16
|
+
value[field]
|
17
|
+
end
|
13
18
|
end
|
14
19
|
rescue NoMethodError
|
15
20
|
nil
|
@@ -30,7 +35,15 @@ module MongoParserRB
|
|
30
35
|
|
31
36
|
def stringify_keys(document)
|
32
37
|
document.reduce({}) do |new_document, (k,v)|
|
33
|
-
new_document[k.to_s] =
|
38
|
+
new_document[k.to_s] = case v
|
39
|
+
when Hash
|
40
|
+
stringify_keys(v)
|
41
|
+
when Array
|
42
|
+
v.map { |e| e.kind_of?(Hash) ? stringify_keys(e) : e }
|
43
|
+
else
|
44
|
+
v
|
45
|
+
end
|
46
|
+
|
34
47
|
new_document
|
35
48
|
end
|
36
49
|
end
|
@@ -23,4 +23,18 @@ class FieldTest < MiniTest::Unit::TestCase
|
|
23
23
|
refute field.in_document?(:custom_data => {:tracked_users => 10})
|
24
24
|
end
|
25
25
|
|
26
|
+
def test_returning_array_element
|
27
|
+
field = MongoParserRB::Field.new(:"something.array.0")
|
28
|
+
assert_equal 1, field.value_in_document(:something => {:array => [1,2]})
|
29
|
+
end
|
30
|
+
|
31
|
+
def test_returning_hash_in_array
|
32
|
+
field = MongoParserRB::Field.new(:"something.array.0.key")
|
33
|
+
document = {:something => {:array => [{:key => 'hello world'}, {:key => 'bye world'}]}}
|
34
|
+
assert_equal 'hello world', field.value_in_document(document)
|
35
|
+
|
36
|
+
field = MongoParserRB::Field.new(:"something.array.1.key")
|
37
|
+
assert_equal 'bye world', field.value_in_document(document)
|
38
|
+
end
|
39
|
+
|
26
40
|
end
|