predicate-rb 1.2.0 → 1.3.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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 241ded1a9fae50e90744cd41b6372d3509221ca23fe1e475fe9451b2f5ecd7a6
4
- data.tar.gz: 97e6115a084326f87aa990d645f37df3cd61db373354e6193f2d1776c5f6cefc
3
+ metadata.gz: 4c1cedd3d6c3165e0fe953b066856cee77898d27f27737cac139d0884edde4de
4
+ data.tar.gz: 0dae4f035cbc083d241e42b86f137087e9793c0d88cadc9b251713d916bc3855
5
5
  SHA512:
6
- metadata.gz: 64db44a9ac0cbfb8660a5caff8ee66d5e6a7fc91638007fdc6cf966d4e85bcb6b390ff34bd4d44ef246e106340192852caaa1afbd2d574071cfdf10ae651d7af
7
- data.tar.gz: e620b8d3b168d2694317c855d12ce843c39aef68d2dbf6d095c1c36068cf6946f797c3886a47fc99183f531ca14e5cfaa71f1bb7872db3de73dc251a0a2503f2
6
+ metadata.gz: 171090b6fc0902970b7c373da1577a1d71aa5a0dc6d27f83c064a9bca43bfdec5598aa3ddfe284915fa62eaf5b3b3b0b2fb3fe63f21b1bf9b1589a56b144e99a
7
+ data.tar.gz: 04a6e29df5cead1449f491842ebfc29060d8b557bcc0b0dfde10d9e5c5c69c31cf9643b961424de8dfb02610eb86574707ded07f81fb3f4bd6a3839a8791b422
data/CHANGELOG.md CHANGED
@@ -6,6 +6,44 @@ workflow refuses to publish a version with no entry — see RELEASING.md.
6
6
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
7
7
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
8
8
 
9
+ ## [1.3.0] - 2026-11-26
10
+
11
+ Versions 1.2.1 and 1.2.2 were never published; their changes ship here.
12
+
13
+ ### Added
14
+ - Opt-in strict mode: `Predicate.define(:leave, strict: true)` (or
15
+ `Predicate::Core.new(:leave, strict: true)`). A predicate that raises now
16
+ raises `Predicate::EvaluationError` (original error as `cause`,
17
+ `predicate_name` set), and calling a predicate or section that is not defined
18
+ raises `Predicate::UndefinedPredicate`. Combinators pass these through, so
19
+ `not_predicate(:blocked)` and `none_of(:blocked)` no longer come out `true`
20
+ when `:blocked` crashed or is a typo. The default is unchanged: failures and
21
+ undefined predicates still read as `false`.
22
+ Through `Predicate::ModelIntegration`, `model.blocked?` raises the same
23
+ errors, reaches predicates defined inside a section, and a `?` method the
24
+ core does not know raises `NoMethodError` instead of returning `false`.
25
+
26
+ ### Changed
27
+ - Section results are cached under their own namespace, so section
28
+ `:group`/`:ready` and a direct predicate `:group_ready` no longer share an
29
+ entry. Cache keys for section predicates therefore differ from 1.2.0; the
30
+ cache is in-memory only, so nothing persisted is affected.
31
+ - `add_section` clears the cache, so replacing a section no longer serves the
32
+ old section's results.
33
+ - Pointed gem metadata and release configuration at the maintainer's personal
34
+ accounts.
35
+
36
+ ### Fixed
37
+ - `thread_safe: true` no longer raises `ThreadError` (reported as `false`) when a
38
+ predicate calls another predicate on the same core; the cache lock is now
39
+ re-entrant for the thread holding it.
40
+ - A predicate that raises is no longer cached as `false`; the next call
41
+ evaluates it again.
42
+ - `validates_numericality_of` and `validates_length_of` returned `false` for a
43
+ non-numeric value or one without a length only because a `LocalJumpError`
44
+ was swallowed, logging "unexpected return" on every such call under Rails.
45
+ They now return `false` directly. Results are unchanged.
46
+
9
47
  ## [1.2.0] - 2026-02-24
10
48
 
11
49
  First public release on RubyGems, as `predicate-rb` (the name `predicate`
data/README.md CHANGED
@@ -256,6 +256,26 @@ end
256
256
  # Uses Mutex to protect cache operations
257
257
  ```
258
258
 
259
+ ### Strict Mode (fail instead of `false`)
260
+
261
+ By default a predicate that raises, or that does not exist, reads as `false` —
262
+ so `not_predicate(:blocked)` reads as `true` when `:blocked` crashed or is
263
+ misspelled. Where a wrong `true` is worse than an exception, opt in:
264
+
265
+ ```ruby
266
+ Predicate.define(:leave, strict: true) do
267
+ blocked { |s| s.fetch(:blocked) }
268
+ not_blocked { |s| not_predicate(:blocked).call(s) }
269
+ end
270
+
271
+ Predicate.for(:leave).call(:not_blocked, {})
272
+ # => raises Predicate::EvaluationError (predicate_name: :blocked, cause: KeyError)
273
+ Predicate.for(:leave).call(:not_bloked, {})
274
+ # => raises Predicate::UndefinedPredicate
275
+ ```
276
+
277
+ Failures are never cached, so the next call evaluates again.
278
+
259
279
  ### Validation Helpers (Rails Integration)
260
280
 
261
281
  ```ruby
@@ -753,7 +773,7 @@ For bugs or feature requests, contact the development team.
753
773
 
754
774
  ## 📄 License
755
775
 
756
- Proprietary - StockLive Internal Use Only
776
+ MIT License. See [LICENSE](LICENSE) for details.
757
777
 
758
778
  ## 👤 Authors
759
779
 
@@ -79,6 +79,9 @@ module Predicate
79
79
  raise ArgumentError, "Invalid predicate type: #{predicate.class}"
80
80
  end
81
81
  rescue StandardError => e
82
+ # Strict mode: a failure must not read as false (and so as true once negated)
83
+ raise if @core.respond_to?(:strict?) && @core.strict?
84
+
82
85
  Rails.logger.error "Combinator predicate failed: #{e.message}" if defined?(Rails) && Rails.respond_to?(:logger)
83
86
  false
84
87
  end
@@ -90,6 +93,9 @@ module Predicate
90
93
  def execute_predicate(predicate, state)
91
94
  predicate.call(state)
92
95
  rescue StandardError => e
96
+ # Strict mode: a failure must not read as false (and so as true once negated)
97
+ raise if @core.respond_to?(:strict?) && @core.strict?
98
+
93
99
  Rails.logger.error "Combinator predicate failed: #{e.message}" if defined?(Rails) && Rails.respond_to?(:logger)
94
100
  false
95
101
  end
@@ -29,7 +29,10 @@ module Predicate
29
29
  # @param entity [Symbol, String] The entity name
30
30
  # @param cache_ttl [Numeric, nil] Cache time-to-live in seconds (nil = no expiration)
31
31
  # @param thread_safe [Boolean] Enable thread-safe cache operations (default: false)
32
- def initialize(entity, cache_ttl: nil, thread_safe: false)
32
+ # @param strict [Boolean] Raise Predicate::EvaluationError instead of returning
33
+ # false when a predicate raises or is undefined (default: false)
34
+ def initialize(entity, cache_ttl: nil, thread_safe: false, strict: false)
35
+ @strict = strict
33
36
  @entity = entity.to_sym
34
37
  @predicates = {}
35
38
  @sections = {}
@@ -45,6 +48,11 @@ module Predicate
45
48
  @cache_mutex = thread_safe ? Mutex.new : nil # Mutex for thread-safety
46
49
  end
47
50
 
51
+ # @return [Boolean] True when failures raise instead of reading as false
52
+ def strict?
53
+ @strict
54
+ end
55
+
48
56
  # Add a predicate to the core
49
57
  # @param name [Symbol, String] The predicate name
50
58
  # @param block [Proc] The predicate logic
@@ -53,8 +61,10 @@ module Predicate
53
61
  def add_predicate(name, &block)
54
62
  raise InvalidPredicate, 'Predicate block is required' unless block_given?
55
63
 
56
- @predicates[name.to_sym] = block
57
- clear_cache! # Clear cache when predicates change
64
+ synchronize_cache do
65
+ @predicates[name.to_sym] = block
66
+ clear_cache! # Clear cache when predicates change
67
+ end
58
68
  end
59
69
 
60
70
  # Add section predicates for grouping related predicates
@@ -68,7 +78,10 @@ module Predicate
68
78
  def add_section(section_name, &block)
69
79
  raise InvalidPredicate, 'Section block is required' unless block_given?
70
80
 
71
- @sections[section_name.to_sym] = block
81
+ synchronize_cache do
82
+ @sections[section_name.to_sym] = block
83
+ clear_cache! # Replacing a section must not serve its old results
84
+ end
72
85
  end
73
86
 
74
87
  # Call a predicate with state
@@ -79,11 +92,7 @@ module Predicate
79
92
  # result = core.call(:has_media, { media_attachment_ids: [1, 2] })
80
93
  def call(name, state)
81
94
  # Wrap entire operation in mutex if thread-safe mode enabled
82
- if @thread_safe
83
- @cache_mutex.synchronize { call_impl(name, state) }
84
- else
85
- call_impl(name, state)
86
- end
95
+ synchronize_cache { call_impl(name, state) }
87
96
  end
88
97
 
89
98
  # Internal implementation of call (extracted for mutex wrapping)
@@ -109,7 +118,11 @@ module Predicate
109
118
 
110
119
  # Find and execute predicate
111
120
  predicate = find_predicate(name)
112
- return false unless predicate
121
+ unless predicate
122
+ raise UndefinedPredicate.new("Undefined predicate: #{name}", predicate_name: name) if @strict
123
+
124
+ return false
125
+ end
113
126
 
114
127
  begin
115
128
  result = predicate.call(state)
@@ -120,9 +133,8 @@ module Predicate
120
133
  track_performance(name, Predicate::Util.now - start_time)
121
134
  result
122
135
  rescue StandardError => e
123
- # Store false result for failed predicates to avoid re-execution
124
- store_in_cache(cache_key, false)
125
136
  track_performance(name, Predicate::Util.now - start_time)
137
+ raise evaluation_error(name, e) if @strict
126
138
 
127
139
  # Log error but don't raise - predicates should be resilient
128
140
  Rails.logger.error "Predicate #{name} failed: #{e.message}" if defined?(Rails) && Rails.respond_to?(:logger)
@@ -139,11 +151,7 @@ module Predicate
139
151
  # result = core.call_section(:media, :has_media, { media_attachment_ids: [1, 2] })
140
152
  def call_section(section_name, predicate_name, state)
141
153
  # Wrap entire operation in mutex if thread-safe mode enabled
142
- if @thread_safe
143
- @cache_mutex.synchronize { call_section_impl(section_name, predicate_name, state) }
144
- else
145
- call_section_impl(section_name, predicate_name, state)
146
- end
154
+ synchronize_cache { call_section_impl(section_name, predicate_name, state) }
147
155
  end
148
156
 
149
157
  # Internal implementation of call_section (extracted for mutex wrapping)
@@ -156,7 +164,8 @@ module Predicate
156
164
 
157
165
  # Use deterministic cache key (same as regular predicates)
158
166
  combined_name = "#{section_name}_#{predicate_name}"
159
- cache_key = create_cache_key(combined_name, state)
167
+ # Namespaced so section :a/:b_c never shares an entry with direct :a_b_c
168
+ cache_key = [:section, section_name.to_sym, predicate_name.to_sym, create_cache_key(nil, state)]
160
169
 
161
170
  # Check cache with hit/miss tracking (same as regular predicates)
162
171
  # Also check TTL validity
@@ -171,12 +180,17 @@ module Predicate
171
180
  # Execute section block to get predicates
172
181
  section_predicates = {}
173
182
  section = @sections[section_name.to_sym]
174
- return false unless section
175
-
176
- section.call(section_predicates)
183
+ section&.call(section_predicates)
177
184
 
178
185
  predicate = section_predicates[predicate_name.to_sym]
179
- return false unless predicate
186
+ unless predicate
187
+ if @strict
188
+ raise UndefinedPredicate.new("Undefined section predicate: #{section_name}/#{predicate_name}",
189
+ predicate_name: combined_name)
190
+ end
191
+
192
+ return false
193
+ end
180
194
 
181
195
  begin
182
196
  result = predicate.call(state)
@@ -188,11 +202,9 @@ module Predicate
188
202
  track_performance(combined_name.to_sym, duration)
189
203
  result
190
204
  rescue StandardError => e
191
- # Use store_in_cache for errors too
192
- store_in_cache(cache_key, false)
193
-
194
205
  duration = Predicate::Util.now - start_time
195
206
  track_performance(combined_name.to_sym, duration)
207
+ raise evaluation_error(combined_name, e) if @strict
196
208
 
197
209
  # Log error but don't raise - predicates should be resilient
198
210
  if defined?(Rails) && Rails.respond_to?(:logger)
@@ -230,12 +242,7 @@ module Predicate
230
242
 
231
243
  # Clear the cache
232
244
  def clear_cache!
233
- if @thread_safe
234
- @cache_mutex.synchronize do
235
- @memoized_results.clear
236
- @cache_timestamps.clear if @cache_ttl
237
- end
238
- else
245
+ synchronize_cache do
239
246
  @memoized_results.clear
240
247
  @cache_timestamps.clear if @cache_ttl
241
248
  end
@@ -262,6 +269,26 @@ module Predicate
262
269
 
263
270
  private
264
271
 
272
+ # Strict mode: wrap a predicate's error, keeping the original as +cause+.
273
+ # An EvaluationError from a nested predicate is passed through unchanged so
274
+ # it still names the predicate that actually failed.
275
+ def evaluation_error(name, error)
276
+ return error if error.is_a?(EvaluationError)
277
+
278
+ EvaluationError.new("Predicate #{name} failed: #{error.message}", predicate_name: name)
279
+ end
280
+
281
+ # Run the block under the cache mutex when thread-safe mode is on.
282
+ # Re-entrant: a predicate that calls another predicate on the same core
283
+ # (or clears its cache) already holds the lock, so it runs the block
284
+ # directly instead of raising ThreadError on a recursive lock.
285
+ def synchronize_cache(&block)
286
+ return yield unless @thread_safe
287
+ return yield if @cache_mutex.owned?
288
+
289
+ @cache_mutex.synchronize(&block)
290
+ end
291
+
265
292
  # Create an optimized cache key from predicate name and state
266
293
  # @param name [Symbol, String] The predicate name
267
294
  # @param state [Hash] The state hash
data/lib/predicate/dsl.rb CHANGED
@@ -49,12 +49,12 @@ module Predicate
49
49
  class Builder
50
50
  attr_reader :entity, :core, :current_section
51
51
 
52
- def initialize(entity, core = nil, cache_ttl: nil, thread_safe: false)
52
+ def initialize(entity, core = nil, cache_ttl: nil, thread_safe: false, strict: false)
53
53
  @entity = entity.to_sym
54
54
  @cache_ttl = cache_ttl
55
55
  @thread_safe = thread_safe
56
56
  # Create core immediately with parameters (needed for predicate definitions)
57
- @core = core || Core.new(@entity, cache_ttl: cache_ttl, thread_safe: thread_safe)
57
+ @core = core || Core.new(@entity, cache_ttl: cache_ttl, thread_safe: thread_safe, strict: strict)
58
58
  @current_section = nil
59
59
  @defined_predicates = {}
60
60
  end
@@ -292,7 +292,7 @@ module Predicate
292
292
 
293
293
  define_predicate(predicate_name) do |state|
294
294
  value = state[field]
295
- return false unless value.is_a?(Numeric)
295
+ next false unless value.is_a?(Numeric)
296
296
 
297
297
  checks = []
298
298
  checks << @core.greater_than?(value, options[:greater_than]) if options[:greater_than]
@@ -326,7 +326,7 @@ module Predicate
326
326
 
327
327
  define_predicate(predicate_name) do |state|
328
328
  value = state[field]
329
- return false unless value.respond_to?(:length)
329
+ next false unless value.respond_to?(:length)
330
330
 
331
331
  length = value.length
332
332
  checks = []
@@ -254,6 +254,16 @@ module Predicate
254
254
  # Only try to call if predicates are loaded and predicate exists
255
255
  if predicates_loaded? && predicate?(predicate_name)
256
256
  call_predicate(predicate_name)
257
+ elsif predicates_loaded? && predicate_instance.strict?
258
+ # Strict mode: let the core answer (it also finds section predicates).
259
+ # A name the core does not know is an ordinary missing method, not false.
260
+ begin
261
+ call_predicate(predicate_name)
262
+ rescue UndefinedPredicate => e
263
+ raise unless e.predicate_name.to_s == predicate_name.to_s
264
+
265
+ super
266
+ end
257
267
  else
258
268
  # Predicate doesn't exist or not loaded, return false for predicate methods
259
269
  false
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Predicate
4
- VERSION = '1.2.0'
4
+ VERSION = '1.3.0'
5
5
  end
data/lib/predicate.rb CHANGED
@@ -35,10 +35,28 @@ module Predicate
35
35
  # Custom exception for predicate-related errors
36
36
  class InvalidPredicate < StandardError; end
37
37
 
38
+ # Raised in strict mode when a predicate cannot produce an answer: its block
39
+ # raised (the original error is available as +cause+), or — see
40
+ # UndefinedPredicate — it does not exist. Outside strict mode both cases are
41
+ # reported as +false+.
42
+ class EvaluationError < StandardError
43
+ attr_reader :predicate_name
44
+
45
+ def initialize(message = nil, predicate_name: nil)
46
+ super(message)
47
+ @predicate_name = predicate_name
48
+ end
49
+ end
50
+
51
+ # Raised in strict mode when the predicate or section called is not defined.
52
+ class UndefinedPredicate < EvaluationError; end
53
+
38
54
  # Main entry point for defining predicates
39
55
  # @param entity [Symbol, String] The entity name (e.g., :assessment, :sale)
40
56
  # @param cache_ttl [Numeric, nil] Cache time-to-live in seconds (nil = no expiration)
41
57
  # @param thread_safe [Boolean] Enable thread-safe cache operations (default: false)
58
+ # @param strict [Boolean] Raise Predicate::EvaluationError instead of returning
59
+ # false when a predicate raises or is undefined (default: false)
42
60
  # @param block [Proc] Block containing predicate definitions
43
61
  # @return [Predicate::Core] The predicate instance
44
62
  # @example
@@ -46,6 +64,11 @@ module Predicate
46
64
  # has_media { |s| is_present?(s[:media_attachment_ids]) }
47
65
  # wizard_complete { |s| has_media(s) && has_title(s) }
48
66
  # end
67
+ # @example Strict: a failed or missing predicate halts instead of reading as false
68
+ # Predicate.define(:leave, strict: true) do
69
+ # blocked { |s| s.fetch(:blocked) }
70
+ # not_blocked { |s| not_predicate(:blocked).call(s) }
71
+ # end
49
72
  # @example With TTL
50
73
  # Predicate.define(:assessment, cache_ttl: 5.minutes) do
51
74
  # has_media { |s| is_present?(s[:media_attachment_ids]) }
@@ -54,8 +77,8 @@ module Predicate
54
77
  # Predicate.define(:assessment, thread_safe: true, cache_ttl: 5.minutes) do
55
78
  # has_media { |s| is_present?(s[:media_attachment_ids]) }
56
79
  # end
57
- def self.define(entity, cache_ttl: nil, thread_safe: false, &block)
58
- builder = DSL::Builder.new(entity, nil, cache_ttl: cache_ttl, thread_safe: thread_safe)
80
+ def self.define(entity, cache_ttl: nil, thread_safe: false, strict: false, &block)
81
+ builder = DSL::Builder.new(entity, nil, cache_ttl: cache_ttl, thread_safe: thread_safe, strict: strict)
59
82
  builder.instance_eval(&block)
60
83
  core = builder.build
61
84
  Registry.register(entity, core)
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: predicate-rb
3
3
  version: !ruby/object:Gem::Version
4
- version: 1.2.0
4
+ version: 1.3.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Nauman Tariq
@@ -56,15 +56,15 @@ files:
56
56
  - lib/predicate/util.rb
57
57
  - lib/predicate/validation.rb
58
58
  - lib/predicate/version.rb
59
- homepage: https://github.com/StockLive-Group/predicate
59
+ homepage: https://github.com/nauman/predicate
60
60
  licenses:
61
61
  - MIT
62
62
  metadata:
63
- homepage_uri: https://github.com/StockLive-Group/predicate
64
- source_code_uri: https://github.com/StockLive-Group/predicate
65
- changelog_uri: https://github.com/StockLive-Group/predicate/blob/main/CHANGELOG.md
66
- bug_tracker_uri: https://github.com/StockLive-Group/predicate/issues
67
- documentation_uri: https://github.com/StockLive-Group/predicate/blob/main/README.md
63
+ homepage_uri: https://github.com/nauman/predicate
64
+ source_code_uri: https://github.com/nauman/predicate
65
+ changelog_uri: https://github.com/nauman/predicate/blob/main/CHANGELOG.md
66
+ bug_tracker_uri: https://github.com/nauman/predicate/issues
67
+ documentation_uri: https://github.com/nauman/predicate/blob/main/README.md
68
68
  rdoc_options: []
69
69
  require_paths:
70
70
  - lib