Skip to content

Commit

Permalink
Merge pull request #16 from lewisf/master
Browse files Browse the repository at this point in the history
Add JSONLogic.uses_data to find all expected variables / provide a means to check if variables are missing
  • Loading branch information
bhgames authored Nov 24, 2019
2 parents 0f52988 + e53deda commit 92d6e31
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
16 changes: 16 additions & 0 deletions lib/json_logic.rb
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,22 @@ def self.apply(logic, data)
Operation.perform(operator, values, data || {})
end

def self.uses_data(logic)
collection = []

operator, values = logic.first
values = [values] unless values.is_a?(Array)
if operator == 'var'
collection.append(values[0])
else
values.each { |val|
collection.concat(uses_data(val))
}
end

return collection.uniq
end

def self.filter(logic, data)
data.select { |d| apply(logic, d) }
end
Expand Down
33 changes: 33 additions & 0 deletions test/json_logic_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -98,4 +98,37 @@ def test_in_with_variable
{ "x" => "foo", "y" => "bar" }
)
end

def test_uses_data
assert_equal ["x", "y"], JSONLogic.uses_data(
{
"in" => [
{"var" => "x"},
{"var" => "y"},
]
}
)
end

def test_uses_data_missing
vars = JSONLogic.uses_data(
{
"in" => [
{"var" => "x"},
{"var" => "y"},
]
}
)

provided_data_missing_y = {
x: 3,
}

provided_data_missing_x = {
y: 4,
}

assert_equal ["y"], JSONLogic.apply({"missing": [vars]}, provided_data_missing_y)
assert_equal ["x"], JSONLogic.apply({"missing": [vars]}, provided_data_missing_x)
end
end

0 comments on commit 92d6e31

Please sign in to comment.