From e53dedac29b46904f7a3ba919079db8b97b72f57 Mon Sep 17 00:00:00 2001 From: Lewis Chung Date: Wed, 25 Sep 2019 23:33:05 -0700 Subject: [PATCH] Add JSONLogic.uses_data to provide a means to find missing variables --- lib/json_logic.rb | 16 ++++++++++++++++ test/json_logic_test.rb | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+) diff --git a/lib/json_logic.rb b/lib/json_logic.rb index 914573e..d4eed59 100644 --- a/lib/json_logic.rb +++ b/lib/json_logic.rb @@ -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 diff --git a/test/json_logic_test.rb b/test/json_logic_test.rb index 72a913f..0d4d192 100644 --- a/test/json_logic_test.rb +++ b/test/json_logic_test.rb @@ -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