Skip to content

Commit f8f404d

Browse files
authored
Merge pull request #9 from ronin/allow-arrays-with-logic
Handle arrays with logic correctly
2 parents bcd4339 + 268cc95 commit f8f404d

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed

lib/json_logic.rb

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,12 @@
44
require 'json_logic/operation'
55
module JSONLogic
66
def self.apply(logic, data)
7+
if logic.is_a?(Array)
8+
return logic.map { |val| apply(val, data) }
9+
end
10+
711
return logic unless logic.is_a?(Hash) # pass-thru
12+
813
data = data.stringify_keys if data.is_a?(Hash) # Stringify keys to keep out problems with symbol/string mismatch
914
operator, values = logic.first # unwrap single-key hash
1015
values = [values] unless values.is_a?(Array) # syntactic sugar

test/json_logic_test.rb

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,12 @@ class JSONLogicTest < Minitest::Test
1515
define_method("test_#{count}") do
1616
result = JSONLogic.apply(pattern[0], pattern[1])
1717
msg = "#{pattern[0].to_json} (data: #{pattern[1].to_json})"
18-
assert_equal(pattern[2], result, msg)
18+
19+
if pattern[2].nil?
20+
assert_nil(result, msg)
21+
else
22+
assert_equal(pattern[2], result, msg)
23+
end
1924
end
2025
count += 1
2126
end
@@ -39,4 +44,19 @@ def test_add_operation
3944
data = JSON.parse(%Q|{"num": 1}|)
4045
assert_equal([6], JSONLogic.apply(rules, data))
4146
end
47+
48+
def test_array_with_logic
49+
assert_equal [1, 2, 3], JSONLogic.apply([1, {"var" => "x"}, 3], {"x" => 2})
50+
51+
assert_equal [42], JSONLogic.apply(
52+
{
53+
"if" => [
54+
{"var" => "x"},
55+
[{"var" => "y"}],
56+
99
57+
]
58+
},
59+
{ "x" => true, "y" => 42}
60+
)
61+
end
4262
end

0 commit comments

Comments
 (0)