Skip to content

Commit

Permalink
Merge pull request #9 from ronin/allow-arrays-with-logic
Browse files Browse the repository at this point in the history
Handle arrays with logic correctly
  • Loading branch information
bhgames authored Oct 31, 2018
2 parents bcd4339 + 268cc95 commit f8f404d
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
5 changes: 5 additions & 0 deletions lib/json_logic.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,12 @@
require 'json_logic/operation'
module JSONLogic
def self.apply(logic, data)
if logic.is_a?(Array)
return logic.map { |val| apply(val, data) }
end

return logic unless logic.is_a?(Hash) # pass-thru

data = data.stringify_keys if data.is_a?(Hash) # Stringify keys to keep out problems with symbol/string mismatch
operator, values = logic.first # unwrap single-key hash
values = [values] unless values.is_a?(Array) # syntactic sugar
Expand Down
22 changes: 21 additions & 1 deletion test/json_logic_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,12 @@ class JSONLogicTest < Minitest::Test
define_method("test_#{count}") do
result = JSONLogic.apply(pattern[0], pattern[1])
msg = "#{pattern[0].to_json} (data: #{pattern[1].to_json})"
assert_equal(pattern[2], result, msg)

if pattern[2].nil?
assert_nil(result, msg)
else
assert_equal(pattern[2], result, msg)
end
end
count += 1
end
Expand All @@ -39,4 +44,19 @@ def test_add_operation
data = JSON.parse(%Q|{"num": 1}|)
assert_equal([6], JSONLogic.apply(rules, data))
end

def test_array_with_logic
assert_equal [1, 2, 3], JSONLogic.apply([1, {"var" => "x"}, 3], {"x" => 2})

assert_equal [42], JSONLogic.apply(
{
"if" => [
{"var" => "x"},
[{"var" => "y"}],
99
]
},
{ "x" => true, "y" => 42}
)
end
end

0 comments on commit f8f404d

Please sign in to comment.