predicate 2.3.3 → 2.7.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (88) hide show
  1. checksums.yaml +5 -5
  2. data/Gemfile +4 -0
  3. data/LICENSE.md +17 -19
  4. data/README.md +467 -0
  5. data/bin/g +2 -0
  6. data/lib/predicate/dsl.rb +138 -0
  7. data/lib/predicate/factory.rb +149 -40
  8. data/lib/predicate/grammar.rb +11 -2
  9. data/lib/predicate/grammar.sexp.yml +31 -0
  10. data/lib/predicate/nodes/${op_name}.rb.jeny +12 -0
  11. data/lib/predicate/nodes/and.rb +9 -0
  12. data/lib/predicate/nodes/binary_func.rb +20 -0
  13. data/lib/predicate/nodes/contradiction.rb +2 -7
  14. data/lib/predicate/nodes/dyadic_comp.rb +1 -3
  15. data/lib/predicate/nodes/empty.rb +14 -0
  16. data/lib/predicate/nodes/eq.rb +11 -3
  17. data/lib/predicate/nodes/expr.rb +5 -3
  18. data/lib/predicate/nodes/has_size.rb +14 -0
  19. data/lib/predicate/nodes/identifier.rb +1 -3
  20. data/lib/predicate/nodes/in.rb +7 -6
  21. data/lib/predicate/nodes/intersect.rb +3 -23
  22. data/lib/predicate/nodes/literal.rb +1 -3
  23. data/lib/predicate/nodes/match.rb +1 -21
  24. data/lib/predicate/nodes/nadic_bool.rb +1 -3
  25. data/lib/predicate/nodes/native.rb +1 -3
  26. data/lib/predicate/nodes/not.rb +1 -3
  27. data/lib/predicate/nodes/opaque.rb +1 -3
  28. data/lib/predicate/nodes/qualified_identifier.rb +1 -3
  29. data/lib/predicate/nodes/set_op.rb +26 -0
  30. data/lib/predicate/nodes/subset.rb +11 -0
  31. data/lib/predicate/nodes/superset.rb +11 -0
  32. data/lib/predicate/nodes/tautology.rb +6 -7
  33. data/lib/predicate/nodes/unary_func.rb +16 -0
  34. data/lib/predicate/nodes/var.rb +46 -0
  35. data/lib/predicate/postgres/ext/factory.rb +28 -0
  36. data/lib/predicate/postgres/ext/to_sequel.rb +26 -0
  37. data/lib/predicate/postgres/ext.rb +2 -0
  38. data/lib/predicate/postgres/pg_array/empty.rb +10 -0
  39. data/lib/predicate/postgres/pg_array/literal.rb +10 -0
  40. data/lib/predicate/postgres/pg_array/overlaps.rb +10 -0
  41. data/lib/predicate/postgres/pg_array.rb +25 -0
  42. data/lib/predicate/postgres/rewriter.rb +49 -0
  43. data/lib/predicate/postgres.rb +4 -0
  44. data/lib/predicate/processors/qualifier.rb +4 -0
  45. data/lib/predicate/processors/renamer.rb +4 -0
  46. data/lib/predicate/processors/to_s.rb +28 -0
  47. data/lib/predicate/processors/unqualifier.rb +4 -0
  48. data/lib/predicate/sequel/to_sequel.rb +5 -1
  49. data/lib/predicate/sugar.rb +47 -0
  50. data/lib/predicate/version.rb +2 -2
  51. data/lib/predicate.rb +28 -4
  52. data/spec/dsl/test_dsl.rb +204 -0
  53. data/spec/dsl/test_evaluate.rb +65 -0
  54. data/spec/dsl/test_respond_to_missing.rb +35 -0
  55. data/spec/dsl/test_to_skake_case.rb +38 -0
  56. data/spec/factory/shared/a_comparison_factory_method.rb +1 -0
  57. data/spec/factory/test_${op_name}.rb.jeny +12 -0
  58. data/spec/factory/test_comp.rb +28 -5
  59. data/spec/factory/test_empty.rb +11 -0
  60. data/spec/factory/test_has_size.rb +11 -0
  61. data/spec/factory/test_match.rb +1 -0
  62. data/spec/factory/test_set_ops.rb +18 -0
  63. data/spec/factory/test_var.rb +22 -0
  64. data/spec/factory/test_vars.rb +27 -0
  65. data/spec/nodes/${op_name}.jeny/test_evaluate.rb.jeny +19 -0
  66. data/spec/nodes/empty/test_evaluate.rb +42 -0
  67. data/spec/nodes/has_size/test_evaluate.rb +44 -0
  68. data/spec/postgres/test_factory.rb +48 -0
  69. data/spec/postgres/test_to_postgres.rb +41 -0
  70. data/spec/postgres/test_to_sequel.rb +44 -0
  71. data/spec/predicate/test_and_split.rb +18 -0
  72. data/spec/predicate/test_attr_split.rb +18 -0
  73. data/spec/predicate/test_constant_variables.rb +24 -2
  74. data/spec/predicate/test_constants.rb +24 -0
  75. data/spec/predicate/test_evaluate.rb +205 -3
  76. data/spec/predicate/test_free_variables.rb +1 -1
  77. data/spec/predicate/test_to_hash.rb +40 -0
  78. data/spec/predicate/test_to_s.rb +37 -0
  79. data/spec/sequel/test_to_sequel.rb +26 -10
  80. data/spec/shared/a_predicate.rb +34 -0
  81. data/spec/spec_helper.rb +18 -1
  82. data/spec/test_predicate.rb +78 -33
  83. data/spec/test_readme.rb +80 -0
  84. data/spec/test_sugar.rb +48 -0
  85. data/tasks/test.rake +3 -3
  86. metadata +67 -11
  87. data/spec/factory/test_between.rb +0 -12
  88. data/spec/factory/test_intersect.rb +0 -12
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
- SHA256:
3
- metadata.gz: 6adb8570080165285172882eb0c0f8216180efa05a58df348055f9a406fcef24
4
- data.tar.gz: 3add1e5ed2a4d728fb92637c8527b8dfeaa2b66f16622a45608aca1d9f079774
2
+ SHA1:
3
+ metadata.gz: 9cef06edb829e0b79b74be5d6f69b329f1cc6656
4
+ data.tar.gz: 32535df41b6b08a634d818308c05424509683b58
5
5
  SHA512:
6
- metadata.gz: 8967a78cd1bbee2b0e2666f0fe853743d98c5be4730c3d263ce30d541387b71de37ac1d3e9544d487c92782795fcdeeb116099b741a362b60390b35aa2834e6a
7
- data.tar.gz: ed564310b25c229a65824e06d6b37353d326a1dd56b00a6723ad669c4321fa2d4e50d660d5c02b66efbaef695a2063504602e9466c7908b0ebf681943dc28571
6
+ metadata.gz: 650836d9f3b0534271a38b2e58f59f4f93aad9fad9b60017777a0c1ab91e373ffe458d1a77bcc2309405c267b657c89121abb401f6687d19f8f79196d209dd06
7
+ data.tar.gz: 70a98a7269cda44050632396a4c90cfafddf16a8b06b1dc76fc1962cab7b4e8520e64244dc20cbf8e2369cbf21e7733f913d7b80cffa4dda0ec26b81decaaaae
data/Gemfile CHANGED
@@ -1,2 +1,6 @@
1
1
  source "https://rubygems.org"
2
2
  gemspec
3
+
4
+ group :development do
5
+ gem "jeny", github: "enspirit/jeny"
6
+ end
data/LICENSE.md CHANGED
@@ -1,22 +1,20 @@
1
- # The MIT Licence
1
+ Copyright (c) 2017-2020 - Enspirit SPRL (Bernard Lambeau)
2
2
 
3
- Copyright (c) 2017 - Enspirit SPRL (Bernard Lambeau)
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
4
10
 
5
- Permission is hereby granted, free of charge, to any person obtaining
6
- a copy of this software and associated documentation files (the
7
- "Software"), to deal in the Software without restriction, including
8
- without limitation the rights to use, copy, modify, merge, publish,
9
- distribute, sublicense, and/or sell copies of the Software, and to
10
- permit persons to whom the Software is furnished to do so, subject to
11
- the following conditions:
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
12
13
 
13
- The above copyright notice and this permission notice shall be
14
- included in all copies or substantial portions of the Software.
15
-
16
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19
- NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
20
- LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
21
- OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
22
- WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,467 @@
1
+ # Predicate
2
+
3
+ ![](https://travis-ci.com/enspirit/predicate.svg?branch=master)
4
+
5
+ Boolean (truth-value) expressions that can be evaluated, manipulated,
6
+ optimized, translated to code, etc.
7
+
8
+ ## Example(s)
9
+
10
+ ```ruby
11
+ # Let's build a simple predicate for 'x = 2 and not(y <= 3)'
12
+ p = Predicate.eq(:x, 2) & !Predicate.lte(:y, 3)
13
+
14
+ p.evaluate(:x => 2, :y => 6)
15
+ # => true
16
+
17
+ p.evaluate(:x => 2, :y => 3)
18
+ # => false
19
+ ```
20
+
21
+ When building complex expressions, you can use the `dsl` method.
22
+
23
+ ```ruby
24
+ # This builds the same predicate
25
+ p = Predicate.dsl{
26
+ eq(:x, 2) & !lte(:y, 3)
27
+ }
28
+ ```
29
+
30
+ The `dsl` block also have all predicates in camelCase, negated, and full text
31
+ variants:
32
+
33
+ ```ruby
34
+ p = Predicate.dsl{
35
+ notEq(:x, "foo") & hasSize(:y, 1..10) & lessThan(:z, 3)
36
+ }
37
+ ```
38
+
39
+ If you have complex expressions where many members apply to the same variable,
40
+ a `currying` dsl extension is provided. It allows using all `dsl` methods
41
+ while omitting their first argument.
42
+
43
+ ```ruby
44
+ # Instead of this
45
+ p = Predicate.gt(:x, 1) & Predicate.lt(:x, 10)
46
+
47
+ # or this
48
+ p = Predicate.dsl{
49
+ gt(:x, 1) & lt(:x, 10)
50
+ }
51
+
52
+ # do this
53
+ p = Predicate.currying(:x){
54
+ gt(1) & lt(10)
55
+ }
56
+ p.evaluate(:x => 6)
57
+ # => true
58
+ ```
59
+
60
+ Predicate also works if you want to evaluate an expression on a single object
61
+ without having to introduce a variable like `:x`...
62
+
63
+ ```ruby
64
+ p = Predicate.currying{
65
+ gt(1) & lt(10)
66
+ }
67
+ p.evaluate(6)
68
+ # => true
69
+ ```
70
+
71
+ ... or, in contrast, if you want to evaluate boolean expressions over more
72
+ complex data structures that a flat Hash like `{:x => 6, ...}`
73
+
74
+ ```ruby
75
+ x, y = Predicate.vars("items.0.price", "items.1.price")
76
+ p = Predicate.eq(x, 6) & Predicate.lt(y, 10)
77
+ p.evaluate({
78
+ items: [
79
+ { name: "Candy", price: 6 },
80
+ { name: "Crush", price: 4 }
81
+ ]
82
+ })
83
+ # => true
84
+ ```
85
+
86
+ The following sections explain a) why we created this library, b) how to build
87
+ expressions, c) what operators are available, and d) how abstract variables
88
+ work and what features are supported when using them (because not all are).
89
+
90
+ ## Rationale
91
+
92
+ This reusable library is used in various ruby gems developed and maintained
93
+ by Enspirit where boolean expressions are first-class citizen. It provides
94
+ a common API for expressing, evaluating, and manipulating them.
95
+
96
+ * [Bmg](https://github.com/enspirit/bmg)
97
+ * [Finitio](https://github.com/blambeau/finitio-rb)
98
+ * [Webspicy](https://github.com/enspirit/webspicy)
99
+
100
+ The library represents an expression as an AST internally. This allows for
101
+ subsequent manipulations & reasoning. Please check the `Predicate::Factory`
102
+ module for details.
103
+
104
+ Best-effort simplifications are also performed at construction and when
105
+ boolean logic is used (and, or, not). For instance, `eq(:x, 6) & eq(:x, 10)`
106
+ yields a `contradiction` predicate. There is currently no way to disable those
107
+ simplifications that were initially implemented for `Bmg`.
108
+
109
+ ## Building expressions
110
+
111
+ The following list of operators is currently available.
112
+
113
+ ### True and False
114
+
115
+ ```ruby
116
+ Predicate.tautology # aka True
117
+ Predicate.contradiction # aka False
118
+ ```
119
+
120
+ ### Logical operators
121
+
122
+ For every valid Predicate instances `p` and `q`:
123
+
124
+ ```ruby
125
+ p & q   # Boolean conjunction
126
+ p | q # Boolean disjunction
127
+ !p # Boolean negation
128
+ ```
129
+
130
+ ### Comparison operators
131
+
132
+ ```ruby
133
+ Predicate.eq(:x, 2) # x = 2
134
+ Predicate.eq(:x, :y) # x = y
135
+ Predicate.neq(:x, 2) # x != 2
136
+ Predicate.neq(:x, :y) # x != y
137
+ Predicate.lt(:x, 2) # x < 2
138
+ Predicate.lt(:x, :y) # x < y
139
+ Predicate.lte(:x, 2) # x <= 2
140
+ Predicate.lte(:x, :y) # x <= y
141
+ Predicate.gt(:x, 2) # x > 2
142
+ Predicate.gt(:x, :y) # x > y
143
+ Predicate.gte(:x, 2) # x >= 2
144
+ Predicate.gte(:x, :y) # x >= y
145
+ ```
146
+
147
+ Shortcuts (translated immediately, no trace kept in AST) :
148
+
149
+ ```ruby
150
+ Predicate.eq(x: 2, y: 6) # eq(:x, 2) & eq(:y, 6)
151
+ Predicate.eq(x: 2, y: :z) # eq(:x, 2) & eq(:y, :z)
152
+ # ... and so on for neq, lt, lte, gt, gte
153
+
154
+ Predicate.between(:x, l, h) # gte(:x, l) & lte(:x, h), for all l and h
155
+ Predicate.in(:x, 1..10) # gte(:x, 1) & lte(:x, 10)
156
+ Predicate.in(:x, 1...10) # gte(:x, 1) & lt(:x, 10)
157
+ #
158
+
159
+ Predicate.is_null(:x) # eq(:x, nil)
160
+ ```
161
+
162
+ ### Set-based operators
163
+
164
+ ```ruby
165
+ Predicate.in(:x, [2, 4, 6]) # x ∈ {2, 4, 6}
166
+ Predicate.in(:x, :y) # x ∈ y
167
+ Predicate.intersect(:x, [2, 4, 6]) # x ∩ {2, 4, 6} ≠ ∅
168
+ Predicate.intersect(:x, :y) # x ∩ y ≠ ∅
169
+ Predicate.subset(:x, [2, 4, 6]) # x ⊆ {2, 4, 6}
170
+ Predicate.subset(:x, :y) # x ⊆ y
171
+ Predicate.superset(:x, [2, 4, 6]) # x ⊇ {2, 4, 6}
172
+ Predicate.superset(:x, :y) # x ⊇ y
173
+ ```
174
+
175
+ ### Other operators
176
+
177
+ The following operators have no clear mathematical semantics. Their semantics
178
+ depends on the underlying type system. Most are currently not supported outside
179
+ of ruby (e.g. SQL compilation). The documentation below applies to a Ruby usage.
180
+
181
+ ```ruby
182
+ Predicate.match(:x, /abc/) # ruby's ===
183
+ Predicate.empty(:x) # ruby's empty?
184
+ Predicate.has_size(:x, 1..10) # ruby's size and ===
185
+ Predicate.has_size(:x, 10) # Same as has_size(:x, 10..10)
186
+ Predicate.has_size(:x, :y) # y must resolve to a Range or Integer
187
+ ```
188
+
189
+ Shortcuts (translated immediately, no trace kept in AST) :
190
+
191
+ ```ruby
192
+ Predicate.min_size(:x, 10) # has_size(:x, 10..)
193
+ Predicate.max_size(:x, 10) # has_size(:x, 0..10)
194
+ ```
195
+
196
+ ### Native expressions
197
+
198
+ Ruby `Proc` can be used to capture complex predicates. Native predicates always
199
+ receive the top evaluation context as first argument.
200
+
201
+ ```ruby
202
+ p = Predicate.native(->(t){
203
+ # t here is the {:x => 2, :y => 6} Hash below
204
+ Foo::Bar.call_to_ruby_code?(t)
205
+ })
206
+ p.evaluate(:x => 2, :y => 6)
207
+ ```
208
+
209
+ Resulting predicates cannot be translated to, e.g. SQL, and typically prevent
210
+ optimizations and manipulations:
211
+
212
+ ## Available operators
213
+
214
+ The following operators are available on predicates.
215
+
216
+ ### Evaluate
217
+
218
+ `Predicate#evaluate` takes a Hash mapping each free variable to a value,
219
+ and returns the Boolean evaluation of the expression.
220
+
221
+ ```ruby
222
+ # Let's build a simple predicate for 'x = 2 and not(y <= 3)'
223
+ p = Predicate.eq(:x, 2) & !Predicate.lte(:y, 3)
224
+
225
+ p.evaluate(:x => 2, :y => 6)
226
+ # => true
227
+ ```
228
+
229
+ ### Rename
230
+
231
+ `Predicate#rename` allows renaming variables.
232
+
233
+ ```ruby
234
+ p = Predicate.eq(:x, 4) # x = 4
235
+ p = p.rename(:x => :z) # z = 4
236
+ ```
237
+
238
+ ### Bind
239
+
240
+ `Predicate#bind` allows late binding of placeholders to values.
241
+
242
+ ```ruby
243
+ pl = Predicate.placeholder
244
+ p = Predicate.eq(:x, pl) # x = _
245
+ p = p.bind(pl, 5) # x = 5
246
+ p.evaluate(:x => 10)
247
+ # => false
248
+ ```
249
+
250
+ ### Quality & Unqualify
251
+
252
+ `Predicate#qualify` allows adding a qualifier to each variable, for
253
+ disambiguation when composing predicates from different contexts.
254
+ `Predicate#unqualify` does the opposite.
255
+
256
+ ```ruby
257
+ p = Predicate.eq(:x, 2) # x = 2
258
+ p.qualify(:t) # t.x = 2
259
+ p.unqualify # x = 2
260
+ ```
261
+
262
+ Qualify accepts a Hash to use different qualifiers for variables.
263
+
264
+ ```ruby
265
+ p = Predicate.eq(x: 2, y: 4) # x = 2 & y = 4
266
+ p.qualify(:x => :t, :y => :s) # t.x = 2 & s.y = 4
267
+ ```
268
+
269
+ ### And split
270
+
271
+ `Predicate#and_split` split a predicate `p` as two predicates `p1` and `p2`
272
+ so that `p <=> p1 & p2` and `p2` makes no reference to any variable of the
273
+ given list.
274
+
275
+ ```ruby
276
+ p = Predicate.eq(x: 2, y: 4) # x = 2 & y = 4
277
+ p1, p2 = p.and_split([:x]) # p1 is x = 2 ; p2 is y = 4
278
+ ```
279
+
280
+ Observe that `and_split` is always possible but may degenerate to an
281
+ uninteresting `p2`, typically when disjunctions are used. For instance,
282
+
283
+ ```ruby
284
+ p = Predicate.eq(x: 2) | Predicate.eq(y: 4) # x = 2 | y = 4
285
+ p1, p2 = p.and_split([:x]) # p1 is x = 2 | y = 4 ; p2 is true
286
+ ```
287
+
288
+ ### Attr split
289
+
290
+ `Predicate#attr_split` can be used to split a predicate `p` as n+1 predicates
291
+ `p1, p2, ..., pn, pz`, such that `p <=> p1 & p2 & ... & pn & pz`. Each
292
+ predicate `pi` makes references to variable `i` only, except `pz` which can
293
+ reference all of them.
294
+
295
+ The result is a Hash mapping each variable to its predicate. A `nil` key maps
296
+ to `pz`.
297
+
298
+ ```ruby
299
+ p = Predicate.eq(x: 2, y: 4) # x = 2 & y = 4
300
+ split = p.attr_split
301
+ # => {
302
+ # :x => Predicate.eq(:x, 2),
303
+ # :y => Predicate.eq(:y, 4)
304
+ # }
305
+ ```
306
+
307
+ ## Working with PostgreSQL
308
+
309
+ (experimental) Predicate supports compiling certain high-level expressions
310
+ to PostgreSQL native operators. It works in an direct or indirect way:
311
+
312
+ ```
313
+ require 'predicate'
314
+ require 'predicate/postgres'
315
+
316
+ # In direct way, you simply create the predicates using PostgreSQL's own
317
+ # operators
318
+ p = Predicate.pg_array_overlaps(:x, ['foo', 'bar'])
319
+ p.to_sequel
320
+
321
+ # In indirect way, you use high-level predicates and convert them to
322
+ # PostgreSQL later using `to_postgres`
323
+ p = Predicate.interect(:x, ['foo', 'bar'])
324
+ p = p.to_postgres
325
+ p.to_sequel
326
+ ```
327
+
328
+ Only a few array operators & translations exist, and only on `varchar[]`
329
+ types. Additional support will be added later. The following
330
+ translations are implemented (and methods on the right directly available
331
+ on the `Predicate` class):
332
+
333
+ ```
334
+ -> pg_array_literal
335
+ intersect -> pg_array_overlaps
336
+ empty -> pg_array_empty
337
+ ```
338
+
339
+ ## Working with abstract variables
340
+
341
+ WARNING: this `var` feature is only compatible with `Predicate#evaluate`
342
+ and `Predicate#bind` so far. Other operators have not been tested and may fail
343
+ in unexpected ways or raise a NotImplementedError. Also, predicates using
344
+ abstract variables are not properly translated to e.g. SQL.
345
+
346
+ By default, Predicate expects variable identifiers to be represented by
347
+ ruby Symbols. `#evaluate` then takes a mapping between variables and values as
348
+ a Hash:
349
+
350
+ ```ruby
351
+ # :x and :y are variable identifiers
352
+ p = Predicate.eq(:x, 2) & !Predicate.lte(:y, 3)
353
+
354
+ # the Hash below is a mapping between variables and values
355
+ p.evaluate(:x => 2, :y => 6)
356
+ # => true
357
+ ```
358
+
359
+ There are situations where you would like variables to be kept simple in
360
+ expressions while evaluating the latter on complex data structures.
361
+
362
+ `Predicate#var` can be used as an abstraction mechanism in such cases.
363
+ It takes a variable definition as first argument and a semantics as second.
364
+ The semantics defines how a value is extracted when the variable value must
365
+ be evaluated.
366
+
367
+ Supported protocols are `:dig`, `:send` and `:public_send`. Only `:dig`
368
+ must be considered safe while the two other ones used with great care.
369
+
370
+ * `:dig` relies on Ruby's `dig` protocol introduced in Ruby 2.3. It
371
+ will work out of the box with Hash, Array, Struct, OpenStruct and
372
+ more generally any object responding to `:dig`:
373
+
374
+ ```ruby
375
+ xyz = Predicate.var([:x, :y, :z], :dig)
376
+ p = Predicate.eq(xyz, 2)
377
+ p.evaluate({ :x => { :y => { :z => 2 } } })
378
+ # => true
379
+ ```
380
+
381
+ When using `:dig` the variable definition can be passed as a String
382
+ that will be automatically decomposed for you. Variable names are
383
+ transformed to Symbols and integer literals to Integers. You must
384
+ use the explicit version above if you don't want those conversions.
385
+
386
+ ```ruby
387
+ # this
388
+ Predicate.var("x.0.y", :dig)
389
+
390
+ # is equivalent to
391
+ Predicate.var([:x, 0, :y], :dig)
392
+ ```
393
+
394
+ * `:send` relies on Ruby's `__send__` method and is generally less
395
+ safe if variable definitions are not strictly controlled. But it
396
+ allows evaluating predicates over any data structure made of pure
397
+ ruby objects:
398
+
399
+ ```ruby
400
+ class C
401
+ attr_reader :x
402
+ def initialize(x)
403
+ @x = x
404
+ end
405
+ end
406
+
407
+ xy = Predicate.var([:x, :y], :send)
408
+ p = Predicate.eq(xy, 2)
409
+ p.evaluate(C.new(OpenStruct.new(y: 2)))
410
+ # => true
411
+ ```
412
+
413
+ The variable can similarly be passed as a dotted String that will be
414
+ decomposed as a sequence of Symbols.
415
+
416
+ ```ruby
417
+ xy = Predicate.var("x.y", :send)
418
+ p = Predicate.eq(xy, 2)
419
+ p.evaluate(C.new(OpenStruct.new(y: 2)))
420
+ # => true
421
+ ```
422
+
423
+ * `:public_send` is similar to `:send` but slightly safer as it only
424
+ allows calling Ruby's public methods.
425
+
426
+ ## Public API
427
+
428
+ This library follows semantics versioning 2.0. Its public API is:
429
+
430
+ * Class methods of the `Predicate` class, such as those covered in the
431
+ "Building expressions" section above.
432
+
433
+ * DSL methods contributed by `Predicate::Factory`, `Predicate::Sugar`,
434
+ and `Predicate::Dsl` modules ; including dynamic ones (negation,
435
+ camelCase, etc.)
436
+
437
+ * Instance methods of the `Predicate` class, such as those covered in the
438
+ "Available operators" section above.
439
+
440
+ * Instance and class methods contributed by plugins (e.g. `predicate/sequel`).
441
+
442
+ * Exception classes: `Predicate::NotSupportedError`,
443
+ `Predicate::UnboundError` and `Predicate::TypeError`.
444
+
445
+ The AST representation of predicate expressions is NOT part of the public API.
446
+ We bump the minor version of the library when it changes, though.
447
+
448
+ Everything else is condidered private and may change any time (i.e. on patch
449
+ releases).
450
+
451
+ ## Contributing
452
+
453
+ Please use github issues and pull requests, and favor the latter if possible.
454
+
455
+ This repository uses the help of [jeny](https://github.com/enspirit/jeny) to
456
+ generate code snippets when adding new predicates. It supports `predicate`
457
+ and `sugar` snippets and add code to be completed in various places:
458
+
459
+ ```
460
+ bundle exec jeny s predicate -d op_name:my_predicate -d arity:unary
461
+ bundle exec jeny s sugar -d op_name:my_shortcut
462
+ ```
463
+
464
+ ## Licence
465
+
466
+ This software is distributed by Enspirit SRL under a MIT Licence. Please
467
+ contact Bernard Lambeau (blambeau@gmail.com) with any question.
data/bin/g ADDED
@@ -0,0 +1,2 @@
1
+ #!/bin/sh
2
+ jeny -d name:$1 s .
@@ -0,0 +1,138 @@
1
+ class Predicate
2
+ class Dsl
3
+
4
+ def initialize(var = nil, allow_currying = true)
5
+ @var = var || ::Predicate.var(".", :dig)
6
+ @allow_currying = allow_currying
7
+ end
8
+
9
+ public # No injection
10
+
11
+ [
12
+ :tautology,
13
+ :contradiction,
14
+ :literal,
15
+ :var,
16
+ :vars,
17
+ :identifier,
18
+ :qualified_identifier,
19
+ :placeholder
20
+ ].each do |name|
21
+ define_method(name) do |*args|
22
+ ::Predicate.send(name)
23
+ end
24
+ end
25
+
26
+ public # All normal
27
+
28
+ [
29
+ :in,
30
+ :intersect,
31
+ :subset,
32
+ :superset,
33
+ #
34
+ :eq,
35
+ :neq,
36
+ :lt,
37
+ :lte,
38
+ :gt,
39
+ :gte,
40
+ #
41
+ :empty,
42
+ :has_size,
43
+ #jeny(predicate) :${op_name},
44
+ ].each do |name|
45
+ define_method(name) do |*args|
46
+ args = apply_curry(name, args, Factory)
47
+ ::Predicate.send(name, *args)
48
+ end
49
+ end
50
+
51
+ public # Operators with options as last arg
52
+
53
+ [
54
+ :match
55
+ ].each do |name|
56
+ define_method(name) do |*args|
57
+ args << {} unless args.last.is_a?(::Hash)
58
+ args = apply_curry(name, args, ::Predicate::Factory)
59
+ ::Predicate.send(name, *args)
60
+ end
61
+ end
62
+
63
+ public # Sugar operators
64
+
65
+ [
66
+ :between,
67
+ :min_size,
68
+ :max_size,
69
+ :is_null,
70
+ #jeny(sugar) :${op_name},
71
+ ].each do |name|
72
+ define_method(name) do |*args|
73
+ args = apply_curry(name, args, ::Predicate::Sugar)
74
+ ::Predicate.send(name, *args)
75
+ end
76
+ end
77
+
78
+ public # Extra names
79
+
80
+ {
81
+ :null => :is_null,
82
+ :size => :has_size,
83
+ :equal => :eq,
84
+ :less_than => :lt,
85
+ :less_than_or_equal => :lte,
86
+ :greater_than => :gt,
87
+ :greater_than_or_equal => :gte
88
+ }.each_pair do |k,v|
89
+ define_method(k) do |*args|
90
+ __send__(v, *args)
91
+ end
92
+ end
93
+
94
+ public
95
+
96
+ def method_missing(n, *args, &bl)
97
+ snaked, to_negate = missing_method_pair(n)
98
+ if snaked == n.to_s && !to_negate
99
+ super
100
+ elsif self.respond_to?(snaked)
101
+ got = __send__(snaked.to_sym, *args, &bl)
102
+ to_negate ? !got : got
103
+ else
104
+ super
105
+ end
106
+ end
107
+
108
+ def respond_to_missing?(n, include_private = false)
109
+ snaked, to_negate = missing_method_pair(n)
110
+ return super if snaked == n.to_s
111
+ self.respond_to?(snaked)
112
+ end
113
+
114
+ private
115
+
116
+ def missing_method_pair(n)
117
+ name, to_negate = n.to_s, false
118
+ if name.to_s[0..2] == "not"
119
+ name, to_negate = name[3..-1], true
120
+ end
121
+ [to_snake_case(name), to_negate]
122
+ end
123
+
124
+ def to_snake_case(str)
125
+ str.gsub(/[A-Z]/){|x| "_#{x.downcase}" }.gsub(/^_/, "")
126
+ end
127
+
128
+ def apply_curry(name, args, on)
129
+ m = on.instance_method(name)
130
+ if @allow_currying and m.arity == 1+args.length
131
+ [@var] + args
132
+ else
133
+ args
134
+ end
135
+ end
136
+
137
+ end # class Dsl
138
+ end # class Predicate