jlogic_ruby 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: f6c8c443ccf8513feef25ce255da07c7d4b1fccf1a24f64c4161ce8c3895100a
4
+ data.tar.gz: c6254d3cf56e8356d40bc14f8428b21ba288db5661983f70b8cf29b9ebee7ce7
5
+ SHA512:
6
+ metadata.gz: cb05203d62a0143a1606eebb1e7a09f831ec80a8a5ba19a2e4a907dc17d5ec3bd508be160b35bae8758288cb0de54645ecf5e4e3d30846b342fd4746d99843a8
7
+ data.tar.gz: 95d6276eb9505af30d82927f8c348f488a068b2be8523a0a8eee3a3be09bb12fd42e5c889d89e14515897ccd5ee84bd1f863f3a09daddaf54f9524fcf96fcdec
data/.gitignore ADDED
@@ -0,0 +1,9 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /Gemfile.lock
4
+ /_yardoc/
5
+ /coverage/
6
+ /doc/
7
+ /pkg/
8
+ /spec/reports/
9
+ /tmp/
data/.travis.yml ADDED
@@ -0,0 +1,5 @@
1
+ sudo: false
2
+ language: ruby
3
+ rvm:
4
+ - 3.1.2
5
+ before_install: gem install bundler -v 2.3.6
data/CHANGELOG.md ADDED
@@ -0,0 +1,15 @@
1
+ # Changelog
2
+
3
+ ## 0.5.0
4
+
5
+ Maintained fork of [bhgames/json-logic-ruby](https://github.com/bhgames/json-logic-ruby), published as `jlogic_ruby` since `json_logic`, `json_logic_ruby`, and similar names are already taken/reserved on RubyGems.
6
+
7
+ - Fix `==`/`!=` treating a missing/nil `var` lookup as equal to `""`, `0`, or `false` (rewrote as proper loose equality per the JsonLogic spec)
8
+ - Fix `reduce` not resolving a logic expression (e.g. `{"var": "..."}`) passed as the initial accumulator value
9
+ - Fix `if` returning the last condition or the full argument list instead of `nil` when nothing matches
10
+ - Fix `in` raising on a `nil` array instead of returning `false`
11
+ - Fix `===` to use Ruby's native `===` instead of `==`, adding `Range`/`Regexp`/`Class` matching (e.g. date-in-range checks) while staying strict for plain values
12
+ - Remove the global `Hash#transform_keys` monkey-patch, which broke the native mapping-hash form (`transform_keys(hash)`) for every other gem in the same process
13
+ - Fix `add_operation` polluting `Object`/`Class` via unsafe metaprogramming
14
+
15
+ All fixes verified against the full official [jsonlogic.com test suite](http://jsonlogic.com/tests.json) (297/297 passing).
@@ -0,0 +1,74 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to making participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, gender identity and expression, level of experience,
9
+ nationality, personal appearance, race, religion, or sexual identity and
10
+ orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ * Using welcoming and inclusive language
18
+ * Being respectful of differing viewpoints and experiences
19
+ * Gracefully accepting constructive criticism
20
+ * Focusing on what is best for the community
21
+ * Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ * The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ * Trolling, insulting/derogatory comments, and personal or political attacks
28
+ * Public or private harassment
29
+ * Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ * Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies both within project spaces and in public spaces
49
+ when an individual is representing the project or its community. Examples of
50
+ representing a project or community include using an official project e-mail
51
+ address, posting via an official social media account, or acting as an appointed
52
+ representative at an online or offline event. Representation of a project may be
53
+ further defined and clarified by project maintainers.
54
+
55
+ ## Enforcement
56
+
57
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
58
+ reported by contacting the project team at kenneth.geerts@up-nxt.com. All
59
+ complaints will be reviewed and investigated and will result in a response that
60
+ is deemed necessary and appropriate to the circumstances. The project team is
61
+ obligated to maintain confidentiality with regard to the reporter of an incident.
62
+ Further details of specific enforcement policies may be posted separately.
63
+
64
+ Project maintainers who do not follow or enforce the Code of Conduct in good
65
+ faith may face temporary or permanent repercussions as determined by other
66
+ members of the project's leadership.
67
+
68
+ ## Attribution
69
+
70
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71
+ available at [http://contributor-covenant.org/version/1/4][version]
72
+
73
+ [homepage]: http://contributor-covenant.org
74
+ [version]: http://contributor-covenant.org/version/1/4/
data/Gemfile ADDED
@@ -0,0 +1,3 @@
1
+ source 'https://rubygems.org'
2
+
3
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2016 Kenneth Geerts, Jordan Prince
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,122 @@
1
+ # json-logic-ruby [![Build Status](https://travis-ci.org/bhgames/json-logic-ruby.svg?branch=master)](https://travis-ci.org/bhgames/json-logic-ruby)
2
+
3
+ Build complex rules, serialize them as JSON, and execute them in ruby.
4
+
5
+ **json-logic-ruby** is a ruby parser for [JsonLogic](http://jsonlogic.com). Other libraries are available for parsing this logic for Python and JavaScript at that link!
6
+
7
+ ## DANGER WILL ROBINSON!
8
+
9
+ This Ruby version of [jwadhams/json-logic](https://github.com/jwadhams/json-logic)
10
+ does not have the same functionality as the original Javascript version. In
11
+ particular, *method* is not implemented at all and *add_operation* can only define
12
+ operations with **_exactly_** one parameter. There are probably other deficiencies
13
+ as well.
14
+
15
+ This does not mean that JsonLogic is not useful... IMHO, it is. However, the class of
16
+ problems it can solve is a subset of the class of problems that
17
+ [jwadhams/json-logic](https://github.com/jwadhams/json-logic) can solve.
18
+
19
+ Contributions of expertise, time and energy are welcome to correct these deficiencies
20
+ and bring the Ruby version up to parity with the Javascript version. Inquire within
21
+ if you are interested.
22
+
23
+ ## Installation
24
+
25
+ `gem install json_logic`
26
+
27
+ ## Why use JsonLogic?
28
+
29
+ If you're looking for a way to share logic between front-end and back-end code, and even store it in a database, JsonLogic might be a fit for you.
30
+
31
+ JsonLogic isn't a full programming language. It's a small, safe way to delegate one decision. You could store a rule in a database to decide later. You could send that rule from back-end to front-end so the decision is made immediately from user input. Because the rule is data, you can even build it dynamically from user actions or GUI input.
32
+
33
+ JsonLogic has no setters, no loops, no functions or gotos. One rule leads to one decision, with no side effects and deterministic computation time.
34
+
35
+ ## Virtues
36
+ 1. Terse.
37
+ 2. Consistent. {"operator" : ["values" ... ]} Always.
38
+ 3. Secure. We never eval(). Rules only have read access to data you provide, and no write access to anything.
39
+ 4. Flexible. Easy to add new operators, easy to build complex structures.
40
+
41
+ ## Examples
42
+
43
+ ### simple
44
+
45
+ ```ruby
46
+ JSONLogic.apply({ "==" => [1, 1] }, {})
47
+ # => true
48
+ ```
49
+
50
+ This is a simple rule, equivalent to 1 == 1. A few things about the format:
51
+
52
+ 1. The operator is always in the 「key」 position. There is only one key per JsonLogic rule.
53
+ 2. The values are typically an array.
54
+ 3. Each value can be a string, number, boolean, array (non-associative), or null
55
+
56
+ ### Compound
57
+
58
+ Here we're beginning to nest rules.
59
+
60
+ ```ruby
61
+ JSONLogic.apply(
62
+ { "and" => [
63
+ { ">" => [3,1] },
64
+ { "<" => [1,3] }]
65
+ }, {})
66
+
67
+ # => true
68
+ ```
69
+
70
+ In an infix language (like JavaScript) this could be written as:
71
+
72
+ ```
73
+ ( (3 > 1) && (1 < 3) )
74
+ ```
75
+
76
+ ### Data-Driven
77
+
78
+ Obviously these rules aren't very interesting if they can only take static literal data. Typically jsonLogic will be called with a rule object and a data object. You can use the var operator to get attributes of the data object:
79
+
80
+ ```ruby
81
+ JSONLogic.apply(
82
+ { "var" => ["a"] }, # Rule
83
+ { "a" => 1, "b" => 2 } # Data
84
+ )
85
+ # => 1
86
+ ```
87
+
88
+ If you like, we support syntactic sugar on unary operators to skip the array around values:
89
+
90
+
91
+ ```ruby
92
+ JSONLogic.apply(
93
+ { "var" => "a" },
94
+ { "a" => 1, "b" => 2 }
95
+ )
96
+ # => 1
97
+ ```
98
+
99
+ You can also use the `var` operator to access an array by numeric index:
100
+
101
+ ```ruby
102
+ JSONLogic.apply(
103
+ { "var" => 1 },
104
+ ["apple", "banana", "carrot"]
105
+ )
106
+ # => "banana"
107
+ ```
108
+
109
+ Here's a complex rule that mixes literals and data. The pie isn't ready to eat unless it's cooler than 110 degrees, and filled with apples.
110
+
111
+ ```ruby
112
+ rules = JSON.parse(%Q|{ "and" : [
113
+ {"<" : [ { "var" : "temp" }, 110 ]},
114
+ {"==" : [ { "var" : "pie.filling" }, "apple" ] }
115
+ ] }|)
116
+
117
+ data = JSON.parse(%Q|{ "temp" : 100, "pie" : { "filling" : "apple" } }|)
118
+
119
+ JSONLogic.apply(rules, data)
120
+
121
+ # => true
122
+ ```
data/Rakefile ADDED
@@ -0,0 +1,10 @@
1
+ require "bundler/gem_tasks"
2
+ require "rake/testtask"
3
+
4
+ Rake::TestTask.new(:test) do |t|
5
+ t.libs << "test"
6
+ t.libs << "lib"
7
+ t.test_files = FileList['test/**/*_test.rb']
8
+ end
9
+
10
+ task default: :test
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "json_logic"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,35 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'json_logic/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = 'jlogic_ruby'
8
+ spec.version = JSONLogic::VERSION
9
+ spec.authors = ['Kenneth Geerts', 'Jordan Prince', 'iamzayn19']
10
+ spec.email = ['Kenneth.Geerts@gmail.com', 'jordanmprince@gmail.com', 'iamzayn19@gmail.com']
11
+ spec.homepage = 'https://github.com/iamzayn19/json-logic-ruby'
12
+ spec.summary = 'Build complex rules, serialize them as JSON, and execute them in ruby'
13
+ spec.description = 'Build complex rules, serialize them as JSON, and execute them in ruby. Maintained fork of json_logic with fixes for nil/== handling, if, reduce, in, === range matching, and the transform_keys core monkey-patch. See http://jsonlogic.com'
14
+ spec.license = 'MIT'
15
+
16
+ spec.metadata = {
17
+ 'source_code_uri' => 'https://github.com/iamzayn19/json-logic-ruby',
18
+ 'bug_tracker_uri' => 'https://github.com/iamzayn19/json-logic-ruby/issues',
19
+ 'changelog_uri' => 'https://github.com/iamzayn19/json-logic-ruby/blob/master/CHANGELOG.md'
20
+ }
21
+
22
+ spec.files = `git ls-files -z`.split("\x0").reject do |f|
23
+ f.match(%r{^(test|spec|features)/})
24
+ end
25
+ spec.require_paths = ['lib']
26
+
27
+ spec.required_ruby_version = '>= 2.2'
28
+
29
+ spec.add_development_dependency 'bundler', '>= 2.0.1'
30
+ spec.add_development_dependency 'rake', '>= 10.0'
31
+ spec.add_development_dependency 'minitest', '>= 5.0'
32
+ spec.add_development_dependency 'byebug'
33
+ spec.add_development_dependency 'pry'
34
+ spec.add_runtime_dependency 'backport_dig' if Gem::Version.new(RUBY_VERSION) < Gem::Version.new('2.3')
35
+ end
@@ -0,0 +1,17 @@
1
+ require 'backport_dig' if Gem::Version.new(RUBY_VERSION) < Gem::Version.new('2.3')
2
+
3
+ class Hash
4
+ def deep_fetch(key, default = nil)
5
+ keys = key.to_s.split('.')
6
+ value = dig(*keys) rescue default
7
+ value.nil? ? default : value # value can be false (Boolean)
8
+ end
9
+ end
10
+
11
+ class Array
12
+ def deep_fetch(index, default = nil)
13
+ indexes = index.to_s.split('.').map(&:to_i)
14
+ value = dig(*indexes) rescue default
15
+ value.nil? ? default : value # value can be false (Boolean)
16
+ end
17
+ end
@@ -0,0 +1,5 @@
1
+ class Hash
2
+ def stringify_keys
3
+ transform_keys(&:to_s)
4
+ end
5
+ end
@@ -0,0 +1,183 @@
1
+ module JSONLogic
2
+ ITERABLE_KEY = "".freeze
3
+
4
+ class Operation
5
+ LAMBDAS = {
6
+ 'var' => ->(v, d) do
7
+ if !(d.is_a?(Hash) || d.is_a?(Array))
8
+ d
9
+ else
10
+ if v == [JSONLogic::ITERABLE_KEY]
11
+ d.is_a?(Array) ? d : d[JSONLogic::ITERABLE_KEY]
12
+ else
13
+ d.deep_fetch(*v)
14
+ end
15
+ end
16
+ end,
17
+ 'missing' => ->(v, d) { v.select { |val| d.deep_fetch(val).nil? } },
18
+ 'missing_some' => ->(v, d) do
19
+ present = v[1] & d.keys
20
+ present.size >= v[0] ? [] : LAMBDAS['missing'].call(v[1], d)
21
+ end,
22
+ 'some' => -> (v,d) do
23
+ return false unless v[0].is_a?(Array)
24
+
25
+ v[0].any? do |val|
26
+ interpolated_block(v[1], val).truthy?
27
+ end
28
+ end,
29
+ 'filter' => -> (v,d) do
30
+ return [] unless v[0].is_a?(Array)
31
+
32
+ v[0].select do |val|
33
+ interpolated_block(v[1], val).truthy?
34
+ end
35
+ end,
36
+ 'substr' => -> (v,d) do
37
+ return v[0][v[1]..-1] unless v[2]
38
+
39
+ limit = v[2] < 0 ? v[2] - 1 : v[1] + v[2] - 1
40
+
41
+ v[0][v[1]..limit]
42
+ end,
43
+ 'none' => -> (v,d) do
44
+ v[0].none? { |val| interpolated_block(v[1], val) }
45
+ end,
46
+ 'all' => -> (v,d) do
47
+ # Difference between Ruby and JSONLogic spec ruby all? with empty array is true
48
+ return false if v[0].empty?
49
+
50
+ v[0].all? do |val|
51
+ interpolated_block(v[1], val)
52
+ end
53
+ end,
54
+ 'reduce' => -> (v,d) do
55
+ initial = JSONLogic.apply(v[2], d)
56
+ return initial unless v[0].is_a?(Array)
57
+
58
+ v[0].inject(initial) do |acc, val|
59
+ interpolated_block(v[1], { "current": val, "accumulator": acc })
60
+ end
61
+ end,
62
+ 'map' => -> (v,d) do
63
+ return [] unless v[0].is_a?(Array)
64
+
65
+ v[0].map do |val|
66
+ interpolated_block(v[1], val)
67
+ end
68
+ end,
69
+ 'if' => ->(v, d) do
70
+ v.each_slice(2) do |condition_and_value|
71
+ # A trailing single-element slice is the final "else" value.
72
+ if condition_and_value.size == 1
73
+ return condition_and_value.first
74
+ else
75
+ condition, value = condition_and_value
76
+ return value if condition.truthy?
77
+ end
78
+ end
79
+ nil
80
+ end,
81
+ '==' => ->(v, d) { loose_equal?(v[0], v[1]) },
82
+ '===' => ->(v, d) { v[0] === v[1] },
83
+ '!=' => ->(v, d) { !loose_equal?(v[0], v[1]) },
84
+ '!==' => ->(v, d) { v[0] != v[1] },
85
+ '!' => ->(v, d) { v[0].falsy? },
86
+ '!!' => ->(v, d) { v[0].truthy? },
87
+ 'or' => ->(v, d) { v.find(&:truthy?) || v.last },
88
+ 'and' => ->(v, d) do
89
+ result = v.find(&:falsy?)
90
+ result.nil? ? v.last : result
91
+ end,
92
+ '?:' => ->(v, d) { LAMBDAS['if'].call(v, d) },
93
+ '>' => ->(v, d) { v.map(&:to_f).each_cons(2).all? { |i, j| i > j } },
94
+ '>=' => ->(v, d) { v.map(&:to_f).each_cons(2).all? { |i, j| i >= j } },
95
+ '<' => ->(v, d) { v.map(&:to_f).each_cons(2).all? { |i, j| i < j } },
96
+ '<=' => ->(v, d) { v.map(&:to_f).each_cons(2).all? { |i, j| i <= j } },
97
+ 'max' => ->(v, d) { v.map(&:to_f).max },
98
+ 'min' => ->(v, d) { v.map(&:to_f).min },
99
+ '+' => ->(v, d) { v.map(&:to_f).reduce(:+) },
100
+ '-' => ->(v, d) { v.map!(&:to_f); v.size == 1 ? -v.first : v.reduce(:-) },
101
+ '*' => ->(v, d) { v.map(&:to_f).reduce(:*) },
102
+ '/' => ->(v, d) { v.map(&:to_f).reduce(:/) },
103
+ '%' => ->(v, d) { v.map(&:to_i).reduce(:%) },
104
+ '^' => ->(v, d) { v.map(&:to_f).reduce(:**) },
105
+ 'merge' => ->(v, d) { v.flatten },
106
+ 'in' => ->(v, d) do
107
+ result = interpolated_block(v[1], d)&.include? v[0]
108
+ result.nil? ? false : result
109
+ end,
110
+ 'cat' => ->(v, d) { v.map(&:to_s).join },
111
+ 'log' => ->(v, d) { puts v }
112
+ }
113
+
114
+ CUSTOM_LAMBDAS = {}
115
+
116
+ def self.interpolated_block(block, data)
117
+ # Make sure the empty var is there to be used in iterator
118
+ JSONLogic.apply(block, data.is_a?(Hash) ? data.merge({"": data}) : { "": data })
119
+ end
120
+
121
+ def self.perform(operator, values, data)
122
+ # If iterable, we can only pre-fill the first element, the second one must be evaluated per element.
123
+ # If not, we can prefill all.
124
+
125
+ interpolated = if is_iterable?(operator)
126
+ [JSONLogic.apply(values[0], data), *values[1..-1]]
127
+ else
128
+ values.map { |val| JSONLogic.apply(val, data) }
129
+ end
130
+
131
+ interpolated.flatten!(1) if interpolated.size == 1 # [['A']] => ['A']
132
+
133
+ return LAMBDAS[operator.to_s].call(interpolated, data) if is_standard?(operator)
134
+ return CUSTOM_LAMBDAS[operator.to_s].call(interpolated, data) if is_custom?(operator)
135
+ raise ArgumentError, "Unknown operator #{operator}"
136
+ end
137
+
138
+ def self.is_standard?(operator)
139
+ LAMBDAS.key?(operator.to_s)
140
+ end
141
+
142
+ # Loose ("soft") equality, mirroring JS `==` semantics per the JsonLogic spec.
143
+ # `nil` (e.g. from a `var` lookup on a missing key) only equals `nil`/`undefined`,
144
+ # never a coerced string/number, since `null == ""` and `null == 0` are both false in JS.
145
+ def self.loose_equal?(a, b)
146
+ return a.nil? && b.nil? if a.nil? || b.nil?
147
+
148
+ a = a ? 1 : 0 if [true, false].include?(a)
149
+ b = b ? 1 : 0 if [true, false].include?(b)
150
+
151
+ if a.is_a?(Numeric) || b.is_a?(Numeric)
152
+ af = numeric_value(a)
153
+ bf = numeric_value(b)
154
+ return false if af.nil? || bf.nil?
155
+ return af == bf
156
+ end
157
+
158
+ a.to_s == b.to_s
159
+ end
160
+
161
+ def self.numeric_value(value)
162
+ return value.to_f if value.is_a?(Numeric)
163
+ return nil unless value.is_a?(String)
164
+ return 0.0 if value.strip.empty?
165
+
166
+ Float(value) rescue nil
167
+ end
168
+
169
+ def self.is_custom?(operator)
170
+ CUSTOM_LAMBDAS.key?(operator.to_s)
171
+ end
172
+
173
+ # Determine if values associated with operator need to be re-interpreted for each iteration(ie some kind of iterator)
174
+ # or if values can just be evaluated before passing in.
175
+ def self.is_iterable?(operator)
176
+ ['filter', 'some', 'all', 'none', 'in', 'map', 'reduce'].include?(operator.to_s)
177
+ end
178
+
179
+ def self.add_operation(operator, function)
180
+ CUSTOM_LAMBDAS[operator.to_s] = function
181
+ end
182
+ end
183
+ end
@@ -0,0 +1,48 @@
1
+ # JsonLogic truthy / falsy logic
2
+ # Cf. http://jsonlogic.com/truthy.html
3
+
4
+ class Object
5
+ def truthy?
6
+ !falsy?
7
+ end
8
+
9
+ def falsy?
10
+ false
11
+ end
12
+ end
13
+
14
+ class NilClass
15
+ def falsy?
16
+ true
17
+ end
18
+ end
19
+
20
+ class FalseClass
21
+ def falsy?
22
+ true
23
+ end
24
+ end
25
+
26
+ class String
27
+ def falsy?
28
+ empty?
29
+ end
30
+ end
31
+
32
+ class Integer
33
+ def falsy?
34
+ zero?
35
+ end
36
+ end
37
+
38
+ class Float
39
+ def falsy?
40
+ zero?
41
+ end
42
+ end
43
+
44
+ class Array
45
+ def falsy?
46
+ empty?
47
+ end
48
+ end
@@ -0,0 +1,3 @@
1
+ module JSONLogic
2
+ VERSION = '0.5.0'
3
+ end
data/lib/json_logic.rb ADDED
@@ -0,0 +1,66 @@
1
+ require 'core_ext/deep_fetch'
2
+ require 'core_ext/stringify_keys'
3
+ require 'json_logic/truthy'
4
+ require 'json_logic/operation'
5
+ module JSONLogic
6
+ def self.apply(logic, data)
7
+ if logic.is_a?(Array)
8
+ logic.map { |val| apply(val, data) }
9
+ elsif !logic.is_a?(Hash)
10
+ # Pass-thru
11
+ logic
12
+ else
13
+ if data.is_a?(Hash) && data.keys.any?(Symbol)
14
+ data = data.stringify_keys
15
+ end
16
+ data ||= {}
17
+
18
+ operator, values = operator_and_values_from_logic(logic)
19
+ Operation.perform(operator, values, data)
20
+ end
21
+ end
22
+
23
+ # Return a list of the non-literal data used. Eg, if the logic contains a {'var' => 'bananas'} operation, the result of
24
+ # uses_data on this logic will be a collection containing 'bananas'
25
+ def self.uses_data(logic)
26
+ collection = []
27
+
28
+ if logic.kind_of?(Hash) || logic.kind_of?(Array) # If we are still dealing with logic, keep going. Else it's a value.
29
+ operator, values = operator_and_values_from_logic(logic)
30
+
31
+ if operator == 'var' # TODO: It may be that non-var operators use data so we may want a flag or collection that indicates data use.
32
+ if values[0] != JSONLogic::ITERABLE_KEY
33
+ collection << values[0]
34
+ end
35
+ else
36
+ values.each do |val|
37
+ collection.concat(uses_data(val))
38
+ end
39
+ end
40
+ end
41
+
42
+ return collection.uniq
43
+ end
44
+
45
+ def self.operator_and_values_from_logic(logic)
46
+ # Unwrap single-key hash
47
+ operator, values = logic.first
48
+
49
+ # Ensure values is an array
50
+ if !values.is_a?(Array)
51
+ values = [values]
52
+ end
53
+
54
+ [operator, values]
55
+ end
56
+
57
+ def self.filter(logic, data)
58
+ data.select { |d| apply(logic, d) }
59
+ end
60
+
61
+ def self.add_operation(operator, function)
62
+ Operation.add_operation(operator, function)
63
+ end
64
+ end
65
+
66
+ require 'json_logic/version'
metadata ADDED
@@ -0,0 +1,139 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: jlogic_ruby
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.5.0
5
+ platform: ruby
6
+ authors:
7
+ - Kenneth Geerts
8
+ - Jordan Prince
9
+ - iamzayn19
10
+ autorequire:
11
+ bindir: bin
12
+ cert_chain: []
13
+ date: 2026-09-24 00:00:00.000000000 Z
14
+ dependencies:
15
+ - !ruby/object:Gem::Dependency
16
+ name: bundler
17
+ requirement: !ruby/object:Gem::Requirement
18
+ requirements:
19
+ - - ">="
20
+ - !ruby/object:Gem::Version
21
+ version: 2.0.1
22
+ type: :development
23
+ prerelease: false
24
+ version_requirements: !ruby/object:Gem::Requirement
25
+ requirements:
26
+ - - ">="
27
+ - !ruby/object:Gem::Version
28
+ version: 2.0.1
29
+ - !ruby/object:Gem::Dependency
30
+ name: rake
31
+ requirement: !ruby/object:Gem::Requirement
32
+ requirements:
33
+ - - ">="
34
+ - !ruby/object:Gem::Version
35
+ version: '10.0'
36
+ type: :development
37
+ prerelease: false
38
+ version_requirements: !ruby/object:Gem::Requirement
39
+ requirements:
40
+ - - ">="
41
+ - !ruby/object:Gem::Version
42
+ version: '10.0'
43
+ - !ruby/object:Gem::Dependency
44
+ name: minitest
45
+ requirement: !ruby/object:Gem::Requirement
46
+ requirements:
47
+ - - ">="
48
+ - !ruby/object:Gem::Version
49
+ version: '5.0'
50
+ type: :development
51
+ prerelease: false
52
+ version_requirements: !ruby/object:Gem::Requirement
53
+ requirements:
54
+ - - ">="
55
+ - !ruby/object:Gem::Version
56
+ version: '5.0'
57
+ - !ruby/object:Gem::Dependency
58
+ name: byebug
59
+ requirement: !ruby/object:Gem::Requirement
60
+ requirements:
61
+ - - ">="
62
+ - !ruby/object:Gem::Version
63
+ version: '0'
64
+ type: :development
65
+ prerelease: false
66
+ version_requirements: !ruby/object:Gem::Requirement
67
+ requirements:
68
+ - - ">="
69
+ - !ruby/object:Gem::Version
70
+ version: '0'
71
+ - !ruby/object:Gem::Dependency
72
+ name: pry
73
+ requirement: !ruby/object:Gem::Requirement
74
+ requirements:
75
+ - - ">="
76
+ - !ruby/object:Gem::Version
77
+ version: '0'
78
+ type: :development
79
+ prerelease: false
80
+ version_requirements: !ruby/object:Gem::Requirement
81
+ requirements:
82
+ - - ">="
83
+ - !ruby/object:Gem::Version
84
+ version: '0'
85
+ description: Build complex rules, serialize them as JSON, and execute them in ruby.
86
+ Maintained fork of json_logic with fixes for nil/== handling, if, reduce, in, ===
87
+ range matching, and the transform_keys core monkey-patch. See http://jsonlogic.com
88
+ email:
89
+ - Kenneth.Geerts@gmail.com
90
+ - jordanmprince@gmail.com
91
+ - iamzayn19@gmail.com
92
+ executables: []
93
+ extensions: []
94
+ extra_rdoc_files: []
95
+ files:
96
+ - ".gitignore"
97
+ - ".travis.yml"
98
+ - CHANGELOG.md
99
+ - CODE_OF_CONDUCT.md
100
+ - Gemfile
101
+ - LICENSE.txt
102
+ - README.md
103
+ - Rakefile
104
+ - bin/console
105
+ - bin/setup
106
+ - json_logic.gemspec
107
+ - lib/core_ext/deep_fetch.rb
108
+ - lib/core_ext/stringify_keys.rb
109
+ - lib/json_logic.rb
110
+ - lib/json_logic/operation.rb
111
+ - lib/json_logic/truthy.rb
112
+ - lib/json_logic/version.rb
113
+ homepage: https://github.com/iamzayn19/json-logic-ruby
114
+ licenses:
115
+ - MIT
116
+ metadata:
117
+ source_code_uri: https://github.com/iamzayn19/json-logic-ruby
118
+ bug_tracker_uri: https://github.com/iamzayn19/json-logic-ruby/issues
119
+ changelog_uri: https://github.com/iamzayn19/json-logic-ruby/blob/master/CHANGELOG.md
120
+ post_install_message:
121
+ rdoc_options: []
122
+ require_paths:
123
+ - lib
124
+ required_ruby_version: !ruby/object:Gem::Requirement
125
+ requirements:
126
+ - - ">="
127
+ - !ruby/object:Gem::Version
128
+ version: '2.2'
129
+ required_rubygems_version: !ruby/object:Gem::Requirement
130
+ requirements:
131
+ - - ">="
132
+ - !ruby/object:Gem::Version
133
+ version: '0'
134
+ requirements: []
135
+ rubygems_version: 3.4.19
136
+ signing_key:
137
+ specification_version: 4
138
+ summary: Build complex rules, serialize them as JSON, and execute them in ruby
139
+ test_files: []