Skip to content

Commit

Permalink
Handle arrays with logic correctly
Browse files Browse the repository at this point in the history
  • Loading branch information
ronin committed Oct 30, 2018
1 parent dc35ea7 commit 268cc95
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
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
15 changes: 15 additions & 0 deletions test/json_logic_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -44,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 268cc95

Please sign in to comment.