Skip to content

Commit

Permalink
Add JSONLogic.uses_data to provide a means to find missing variables
Browse files Browse the repository at this point in the history
  • Loading branch information
lewisf committed Sep 26, 2019
1 parent 0f52988 commit e53deda
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 e53deda

Please sign in to comment.