predicate-rb 1.2.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.
data/README.md ADDED
@@ -0,0 +1,764 @@
1
+
2
+ > **Status:** Early-stage gem (production-running) • **Origin:** Extracted from StockLive • **Focus:** Isolate decision logic for complex, interlinked flows
3
+
4
+ ---
5
+
6
+ ## ⚠️ Early-stage / Extracted-from-Production Notice
7
+
8
+ Predicate is an **early-stage library** that was **extracted from the StockLive codebase** as part of a broader effort to pull critical “decision logic” out of a large Rails app and into **isolated, composable layers**.
9
+
10
+ In StockLive we had **big, heavily interlinked, dependency-heavy long-form workflows** (wizards, conditional steps, permission gates, grouped validations). Over time, this logic became **scattered across controllers, forms, policies, models, and views**, which made change risk high and testing slow.
11
+
12
+ This gem is one piece of that extraction series:
13
+ - **Predicate layer** (this repository): centralized boolean rules / readiness / gating
14
+ - Related extractions (separate repos or upcoming): **wizard flow**, **permissions**, and **grouping** layers
15
+
16
+ **Important:** Although Predicate is **running in production**, the public gem is still **evolving**:
17
+ - APIs and DSL may change
18
+ - documentation may lag behind features
19
+ - edge-cases are being hardened as more patterns are extracted
20
+
21
+ **AI-assisted, but human-designed:** AI helped accelerate implementation and documentation, but the architecture and patterns were **designed first on paper** and validated against real production needs.
22
+
23
+ If you adopt it, do so with the expectation that you may need to:
24
+ - pin versions
25
+ - review upgrades carefully
26
+ - contribute fixes/patterns as new real-world cases surface
27
+
28
+
29
+ # Predicate Library
30
+
31
+ A lightweight, high-performance predicate evaluation library for Ruby/Rails applications with automatic caching, TTL support, and thread-safe operations.
32
+
33
+ ## 💡 Why This Exists
34
+
35
+ Rails apps tend to repeat the same decision logic in three places:
36
+
37
+ - Controllers (`before_action` filters, multi-step wizards)
38
+ - Models/helpers (validations, scopes, callbacks)
39
+ - Front-end code (React/Vue components mirroring server rules)
40
+
41
+ We built Predicate to centralize those boolean rules. Define the logic once,
42
+ share it between controllers/models/tests, and expose the same truth to the
43
+ front-end (JSON endpoints or server-rendered flags). The goals:
44
+
45
+ 1. **Reduce duplication** – No more copy/pasted "can_publish?" guards.
46
+ 2. **Keep JS thin** – Let Rails compute the booleans; the UI just renders them.
47
+ 3. **Improve confidence** – Predicates are pure functions with deterministic
48
+ caching, so tests can focus on business intent rather than wiring.
49
+ 4. **Reusable across projects** – As a standalone gem, predicate logic can be
50
+ shared across multiple services and applications.
51
+
52
+ ## 🎯 Features
53
+
54
+ - **Pure Boolean Logic** - All predicates return `true` or `false` (never `nil`)
55
+ - **Meta-Programming DSL** - English-like syntax with `method_missing` magic
56
+ - **Collision-Free Caching** - SHA256-based deterministic cache keys
57
+ - **TTL Cache Expiration** - Optional time-based cache invalidation
58
+ - **Thread-Safe Operations** - Mutex-protected cache for Puma/Sidekiq
59
+ - **Rails Integration** - Seamless ActiveRecord model integration
60
+ - **Validation Helpers** - Auto-generate predicates from Rails validations
61
+ - **Boolean Combinators** - AND, OR, NOT, XOR conditional logic
62
+ - **Section Grouping** - Organize related predicates
63
+ - **Performance Monitoring** - Built-in statistics and tracking
64
+ - **LRU Cache Eviction** - Smart memory management (1000 entry limit)
65
+
66
+ ## 📦 Installation
67
+
68
+ ### As a Gem
69
+
70
+ Published on RubyGems as `predicate-rb` (the name `predicate` belongs to an
71
+ unrelated gem). The library is still required as `predicate`.
72
+
73
+ Add to your Gemfile:
74
+
75
+ ```ruby
76
+ gem 'predicate-rb'
77
+
78
+ # Or from a local path during development
79
+ # gem 'predicate-rb', path: '../predicate'
80
+ ```
81
+
82
+ Then run:
83
+
84
+ ```bash
85
+ bundle install
86
+ ```
87
+
88
+ The gem will automatically integrate with Rails via Railtie if Rails is detected.
89
+
90
+ ## 🚀 Quick Start
91
+
92
+ ### 1. Define Predicates
93
+
94
+ ```ruby
95
+ Predicate.define(:assessment) do
96
+ has_media { |s| present?(s[:media_attachment_ids]) }
97
+ has_title { |s| present?(s[:title]) }
98
+ wizard_complete { |s| has_media(s) && has_title(s) }
99
+ end
100
+ ```
101
+
102
+ ### 2. Use in Models
103
+
104
+ ```ruby
105
+ class Assessment < ApplicationRecord
106
+ include Predicate::ModelIntegration
107
+ end
108
+
109
+ # Automatic methods on model instances:
110
+ assessment = Assessment.first
111
+ assessment.has_media? # => true
112
+ assessment.wizard_complete? # => false
113
+ ```
114
+
115
+ ### 3. Call Directly
116
+
117
+ ```ruby
118
+ predicates = Predicate.for(:assessment)
119
+ state = { media_attachment_ids: [1, 2], title: 'Test' }
120
+
121
+ predicates.call(:has_media, state) # => true
122
+ predicates.call(:wizard_complete, state) # => true
123
+ ```
124
+
125
+ ## 🧩 Full Integration Workflow
126
+
127
+ To run Predicate across controllers, views, jobs, and front-end consumers:
128
+
129
+ 1. **Create a predicate directory**
130
+
131
+ ```bash
132
+ mkdir -p app/predicates
133
+ ```
134
+
135
+ 2. **Generate a predicate skeleton** (from `rails console` or `rails runner`):
136
+
137
+ ```ruby
138
+ Predicate::ModelIntegration::PredicateFileGenerator.generate_for_model(
139
+ Assessment,
140
+ Rails.root.join('app/predicates/assessment_predicate.rb')
141
+ )
142
+ ```
143
+
144
+ 3. **Include the integration module** in your model:
145
+
146
+ ```ruby
147
+ class Assessment < ApplicationRecord
148
+ include Predicate::ModelIntegration
149
+ end
150
+ ```
151
+
152
+ 4. **Define predicates** inside the generated file.
153
+
154
+ 5. **Expose results everywhere**: `assessment.has_media?` in controllers/views,
155
+ JSON endpoints for React/Vue, and direct `Predicate.for(:assessment)` calls in
156
+ jobs or services.
157
+
158
+ ## 🧪 End-to-End Example
159
+
160
+ ### Definition (`app/predicates/assessment_predicate.rb`)
161
+
162
+ ```ruby
163
+ Predicate.define(:assessment, cache_ttl: 5.minutes, thread_safe: true) do
164
+ has_media { |s| s[:media_attachment_ids].any? }
165
+ has_title { |s| s[:title].present? }
166
+
167
+ wizard_complete do |state|
168
+ has_media(state) && has_title(state)
169
+ end
170
+ end
171
+ ```
172
+
173
+ ### Usage & Results
174
+
175
+ ```ruby
176
+ assessment = Assessment.find(42)
177
+
178
+ assessment.has_media? # => true
179
+ assessment.has_title? # => false
180
+ assessment.wizard_complete? # => false
181
+
182
+ state = assessment.attributes.symbolize_keys
183
+ Predicate.for(:assessment).call(:wizard_complete, state)
184
+ # => false
185
+ ```
186
+
187
+ > Need more scenarios? `EXAMPLES.md` contains 30+ real-world definitions with
188
+ > matching usage/output snippets.
189
+
190
+
191
+ ## 📖 Complete Usage Guide
192
+
193
+ ### Basic Predicates
194
+
195
+ ```ruby
196
+ Predicate.define(:product) do
197
+ # Simple presence checks
198
+ has_name { |s| present?(s[:name]) }
199
+ has_price { |s| present?(s[:price]) }
200
+
201
+ # Numeric comparisons
202
+ in_stock { |s| s[:quantity] > 0 }
203
+ on_sale { |s| s[:discount] > 0 }
204
+
205
+ # Combining predicates
206
+ ready_to_sell { |s| has_name(s) && has_price(s) && in_stock(s) }
207
+ end
208
+ ```
209
+
210
+ ### Section-Based Organization
211
+
212
+ ```ruby
213
+ Predicate.define(:sale) do
214
+ section :validation do
215
+ has_customer { |s| present?(s[:customer_id]) }
216
+ has_items { |s| s[:line_items]&.any? }
217
+ ready_to_invoice { |s| has_customer(s) && has_items(s) }
218
+ end
219
+
220
+ section :permissions do
221
+ can_edit { |s| s[:user_role] == 'admin' }
222
+ can_delete { |s| can_edit(s) && s[:status] == 'draft' }
223
+ end
224
+ end
225
+
226
+ # Call section predicates
227
+ predicates = Predicate.for(:sale)
228
+ predicates.call_section(:validation, :ready_to_invoice, sale_state)
229
+ # => true/false
230
+ ```
231
+
232
+ ### TTL (Time-To-Live) Cache Expiration
233
+
234
+ ```ruby
235
+ # Cache results for 5 minutes
236
+ Predicate.define(:expensive_check, cache_ttl: 5.minutes) do
237
+ api_result { |s| expensive_api_call(s[:id]) }
238
+ complex_calculation { |s| heavy_computation(s[:data]) }
239
+ end
240
+
241
+ # First call: executes and caches
242
+ # Within 5 minutes: returns cached result
243
+ # After 5 minutes: cache expires, re-executes
244
+ ```
245
+
246
+ ### Thread-Safe Mode (for Puma/Sidekiq)
247
+
248
+ ```ruby
249
+ # Enable thread-safe cache operations
250
+ Predicate.define(:concurrent_checks, thread_safe: true) do
251
+ check_status { |s| s[:status] == 'active' }
252
+ check_inventory { |s| s[:quantity] > 0 }
253
+ end
254
+
255
+ # Safe for concurrent access from multiple threads
256
+ # Uses Mutex to protect cache operations
257
+ ```
258
+
259
+ ### Validation Helpers (Rails Integration)
260
+
261
+ ```ruby
262
+ Predicate.define(:user) do
263
+ # Auto-generates predicates from validations
264
+ validates_presence_of(:name, :email)
265
+ validates_format_of(:email, with: /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i)
266
+ validates_numericality_of(:age, greater_than: 0, less_than: 150)
267
+ validates_length_of(:password, minimum: 8)
268
+ end
269
+
270
+ # Generates predicates:
271
+ # - has_name
272
+ # - has_email
273
+ # - required_fields
274
+ # - valid_email_format
275
+ # - valid_age
276
+ # - valid_password_length
277
+
278
+ predicates = Predicate.for(:user)
279
+ predicates.call(:has_name, { name: 'John' }) # => true
280
+ predicates.call(:valid_email_format, { email: 'invalid' }) # => false
281
+ ```
282
+
283
+ ### English-Like Helpers
284
+
285
+ The library provides 27 English-like helper methods for common checks:
286
+
287
+ ```ruby
288
+ Predicate.define(:user) do
289
+ # Presence/Blank checks
290
+ has_email { |s| present?(s[:email]) }
291
+ no_email { |s| blank?(s[:email]) }
292
+
293
+ # Boolean helpers
294
+ is_enabled { |s| truthy?(s[:enabled]) }
295
+ is_disabled { |s| falsy?(s[:enabled]) }
296
+ is_inverted { |s| not?(s[:active]) }
297
+
298
+ # Type checks
299
+ is_string { |s| is_type?(s[:value], String) }
300
+ is_array { |s| is_type?(s[:value], Array) }
301
+ is_one_of_types { |s| is_one_of?(s[:value], [String, Integer]) }
302
+
303
+ # Collection checks
304
+ has_tags { |s| has_elements?(s[:tags]) }
305
+ has_metadata { |s| has_keys?(s[:metadata]) }
306
+
307
+ # Value checks
308
+ is_valid_status { |s| is_one_of_values?(s[:status], %w[active pending]) }
309
+ is_invalid_status { |s| is_not_one_of_values?(s[:status], %w[banned deleted]) }
310
+
311
+ # Comparison helpers
312
+ age_valid { |s|
313
+ greater_than?(s[:age], 0) && less_than?(s[:age], 150)
314
+ }
315
+ age_range { |s| in_range?(s[:age], 18..100) }
316
+
317
+ # String helpers
318
+ name_length_valid { |s|
319
+ min_length?(s[:name], 3) && max_length?(s[:name], 50)
320
+ }
321
+ email_valid { |s| matches?(s[:email], /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i) }
322
+
323
+ # Math helpers
324
+ is_positive { |s| positive?(s[:amount]) }
325
+ is_negative { |s| negative?(s[:balance]) }
326
+ is_zero { |s| zero?(s[:balance]) }
327
+
328
+ # Equality checks
329
+ account_active { |s| equal_to?(s[:status], 'active') }
330
+ account_inactive { |s| not_equal_to?(s[:status], 'active') }
331
+ end
332
+ ```
333
+
334
+ **Complete Helper List:**
335
+ - **Presence**: `present?(value)`, `blank?(value)`
336
+ - **Boolean**: `not?(value)`, `truthy?(value)`, `falsy?(value)`
337
+ - **Math**: `positive?(value)`, `negative?(value)`, `zero?(value)`
338
+ - **Collections**: `has_elements?(value)`, `has_keys?(value)`
339
+ - **String Length**: `min_length?(value, min)`, `max_length?(value, max)`
340
+ - **Value Comparison**: `min_value?(value, min)`, `max_value?(value, max)`
341
+ - **Range**: `in_range?(value, range)`, `matches?(value, pattern)`
342
+ - **Type Checks**: `is_type?(value, type)`, `is_one_of?(value, types)`
343
+ - **Value Membership**: `is_one_of_values?(value, values)`, `is_not_one_of_values?(value, values)`
344
+ - **Equality**: `equal_to?(value, other)`, `not_equal_to?(value, other)`
345
+ - **Numeric**: `greater_than?(value, other)`, `less_than?(value, other)`, `greater_than_or_equal_to?(value, other)`, `less_than_or_equal_to?(value, other)`
346
+
347
+ ### Boolean Combinators
348
+
349
+ ```ruby
350
+ Predicate.define(:complex) do
351
+ cond_a { |s| s[:a] == 1 }
352
+ cond_b { |s| s[:b] == 2 }
353
+ cond_c { |s| s[:c] == 3 }
354
+
355
+ # Built-in combinators
356
+ all_true { |s| and_all(cond_a(s), cond_b(s), cond_c(s)) }
357
+ any_true { |s| or_any(cond_a(s), cond_b(s), cond_c(s)) }
358
+ not_a { |s| not?(cond_a(s)) }
359
+ xor_check { |s| xor(cond_a(s), cond_b(s)) }
360
+ end
361
+ ```
362
+
363
+ ## 🎮 Rails Console Examples
364
+
365
+ ### Basic Usage
366
+
367
+ ```ruby
368
+ # Start Rails console
369
+ rails c
370
+
371
+ # Define predicates
372
+ Predicate.define(:product) do
373
+ in_stock { |s| s[:quantity] > 0 }
374
+ on_sale { |s| s[:discount] > 0 }
375
+ featured { |s| in_stock(s) && on_sale(s) }
376
+ end
377
+
378
+ # Test predicates
379
+ predicates = Predicate.for(:product)
380
+ predicates.call(:featured, { quantity: 10, discount: 15 })
381
+ # => true
382
+
383
+ # Check performance stats
384
+ predicates.performance_stats
385
+ # => {:featured=>{:calls=>1, :total_time=>0.0001, :average_time=>0.0001, :min_time=>0.0001, :max_time=>0.0001}}
386
+
387
+ # Check cache stats
388
+ predicates.cache_stats
389
+ # => {:cached_results=>1, :predicates=>3, :sections=>0, :cache_hits=>0, :cache_misses=>1, :cache_hit_ratio=>0.0}
390
+ ```
391
+
392
+ ### With Rails Models
393
+
394
+ ```ruby
395
+ # In app/models/assessment.rb
396
+ class Assessment < ApplicationRecord
397
+ include Predicate::ModelIntegration
398
+ end
399
+
400
+ # In app/predicates/assessment_predicates.rb
401
+ Predicate.define(:assessment) do
402
+ has_media { |s| present?(s[:media_attachment_ids]) }
403
+ has_title { |s| present?(s[:title]) && s[:title].length >= 3 }
404
+ has_description { |s| present?(s[:description]) && s[:description].length >= 10 }
405
+
406
+ content_complete { |s| has_title(s) && has_description(s) }
407
+ wizard_complete { |s| has_media(s) && content_complete(s) }
408
+ end
409
+
410
+ # In Rails console
411
+ rails c
412
+
413
+ assessment = Assessment.first
414
+ assessment.has_media? # => true
415
+ assessment.wizard_complete? # => false
416
+
417
+ # Force reload predicates (during development)
418
+ Assessment.load_predicates!(force_reload: true)
419
+ ```
420
+
421
+ ### Testing Cache Behavior
422
+
423
+ ```ruby
424
+ rails c
425
+
426
+ Predicate.define(:test, cache_ttl: 10.seconds) do
427
+ timestamp { |s| Time.now.to_f }
428
+ end
429
+
430
+ predicates = Predicate.for(:test)
431
+
432
+ # First call
433
+ result1 = predicates.call(:timestamp, {})
434
+ # => 1699876543.123
435
+
436
+ # Immediate second call (cached)
437
+ result2 = predicates.call(:timestamp, {})
438
+ # => 1699876543.123 (same as first!)
439
+
440
+ # Wait 11 seconds...
441
+ sleep 11
442
+
443
+ # After TTL expiry (new value)
444
+ result3 = predicates.call(:timestamp, {})
445
+ # => 1699876554.789 (different!)
446
+
447
+ # Check cache stats
448
+ predicates.cache_stats
449
+ # => {:cache_hits=>1, :cache_misses=>2, :cache_hit_ratio=>0.333}
450
+ ```
451
+
452
+ ### Thread-Safety Testing
453
+
454
+ ```ruby
455
+ rails c
456
+
457
+ Predicate.define(:counter, thread_safe: true) do
458
+ count do |s|
459
+ s[:value] ||= 0
460
+ s[:value] + 1
461
+ end
462
+ end
463
+
464
+ predicates = Predicate.for(:counter)
465
+
466
+ # Spawn multiple threads
467
+ threads = 10.times.map do |i|
468
+ Thread.new do
469
+ predicates.call(:count, { id: i, value: i * 10 })
470
+ end
471
+ end
472
+
473
+ threads.each(&:join)
474
+
475
+ # Check cache (should have 10 entries, no corruption)
476
+ predicates.cache_stats
477
+ # => {:cached_results=>10, :cache_hits=>0, :cache_misses=>10}
478
+ ```
479
+
480
+ ## 🧪 Testing
481
+
482
+ ### Run All Tests
483
+
484
+ ```bash
485
+ cd lib/predicate
486
+ ruby test_runner.rb
487
+ # or
488
+ rake test
489
+ ```
490
+
491
+ ### Run Specific Tests
492
+
493
+ ```bash
494
+ ruby -Ilib -Itest test/core_test.rb
495
+ ruby -Ilib -Itest test/ttl_test.rb
496
+ ruby -Ilib -Itest test/thread_safety_test.rb
497
+ ```
498
+
499
+ ### Test Results
500
+
501
+ ```
502
+ ✅ ALL TESTS PASS: 183 runs, 508 assertions, 0 failures, 0 errors
503
+
504
+ Test Coverage:
505
+ ✅ Core Tests - Core engine functionality
506
+ ✅ DSL Tests - Builder and DSL features
507
+ ✅ Combinators Tests - Boolean logic operators
508
+ ✅ Cache Collision Tests - SHA256 collision-free keys
509
+ ✅ Model Integration Tests - Rails ActiveRecord integration
510
+ ✅ TTL Tests - Time-based cache expiration
511
+ ✅ Thread-Safety Tests - Concurrent access protection
512
+ ✅ Validation Helper Tests - Rails validation integration
513
+ ✅ Force Reload Tests - Development workflow
514
+ ✅ Performance Tests - Metrics tracking
515
+ ✅ Section Tests - Section caching guardrails
516
+ ```
517
+
518
+ ## 📊 Performance
519
+
520
+ ### Cache Characteristics
521
+
522
+ - **Cache Size**: 1000 entries (default)
523
+ - **Eviction Strategy**: LRU (removes oldest 25% when full)
524
+ - **TTL Cleanup**: Periodic cleanup every 100 writes
525
+ - **Cache Keys**: SHA256-based (first 16 chars)
526
+ - **Hit Rate**: Typically 70-90% for repeated evaluations
527
+
528
+ ### Performance Stats
529
+
530
+ ```ruby
531
+ predicates = Predicate.for(:assessment)
532
+ stats = predicates.performance_stats
533
+
534
+ # Returns:
535
+ {
536
+ has_media: {
537
+ calls: 150,
538
+ total_time: 0.045,
539
+ average_time: 0.0003,
540
+ min_time: 0.0001,
541
+ max_time: 0.002
542
+ }
543
+ }
544
+ ```
545
+
546
+ ### Complexity
547
+
548
+ - Cache lookup: O(1) with SHA256 hash
549
+ - Cache insertion: O(1) average
550
+ - Cache eviction: O(n/4) when limit reached
551
+ - TTL cleanup: O(n) every 100 writes
552
+ - Thread-safe overhead: ~10-20% with Mutex
553
+
554
+ ## 🏗️ Architecture
555
+
556
+ ```
557
+ Predicate Library
558
+ ├── Predicate::Core # Evaluation engine
559
+ │ ├── Caching (SHA256 keys, LRU eviction)
560
+ │ ├── TTL expiration
561
+ │ ├── Thread-safety (Mutex)
562
+ │ ├── Performance tracking
563
+ │ └── English helpers
564
+ ├── Predicate::DSL # Builder with method_missing
565
+ │ ├── Predicate definitions
566
+ │ ├── Section grouping
567
+ │ └── Validation helpers
568
+ ├── Predicate::Combinators # Boolean logic operators
569
+ ├── Predicate::Registry # Singleton storage
570
+ └── Predicate::ModelIntegration # Rails ActiveRecord integration
571
+ ```
572
+
573
+ ## 📁 Project Structure
574
+
575
+ ```
576
+ lib/predicate/
577
+ ├── lib/
578
+ │ ├── predicate.rb # Main entry point & Registry
579
+ │ └── predicate/
580
+ │ ├── core.rb # Evaluation engine
581
+ │ ├── dsl.rb # Meta-programming DSL
582
+ │ ├── combinators.rb # Boolean operators
583
+ │ └── model_integration.rb # Rails integration
584
+ ├── test/ # Test suite (14 files)
585
+ │ ├── core_test.rb
586
+ │ ├── ttl_test.rb
587
+ │ ├── thread_safety_test.rb
588
+ │ └── ... (11 more test files)
589
+ ├── doc/ # Generated RDoc (git-ignored)
590
+ ├── README.md # This file
591
+ ├── Rakefile # Test tasks
592
+ ├── Gemfile # Dependencies
593
+ └── predicate.gemspec # Gem specification
594
+ ```
595
+
596
+ ## 📚 Documentation
597
+
598
+ ### RDoc
599
+
600
+ Generate comprehensive API documentation:
601
+
602
+ ```bash
603
+ cd lib/predicate
604
+ rdoc --output doc --main README.md --title "Predicate Library Documentation" lib/ README.md
605
+ open doc/index.html
606
+ ```
607
+
608
+ Coverage: **84.62%** (121 out of 143 items documented)
609
+
610
+ ### Guides
611
+
612
+ - **[EXAMPLES.md](EXAMPLES.md)** — Comprehensive examples with 30 scenarios covering all features and practical patterns
613
+ - **Basic Features** (1-15): Predicates, sections, validation helpers, combinators, caching, threading
614
+ - **Real-World Use Cases** (16-24): API validation, feature flags, webhooks, RBAC, workflows, batch processing
615
+ - **Refactoring Patterns** (25-30): Controllers, helpers, views, policies, forms, background jobs
616
+ - Before/after comparisons showing code reduction and performance improvements
617
+ - Generic examples applicable to any Rails application
618
+
619
+ ## 🎯 Use Cases
620
+
621
+ ### 1. Multi-Step Form/Wizard Completion
622
+
623
+ ```ruby
624
+ Predicate.define(:onboarding) do
625
+ step1_complete { |user| present?(user[:email]) && present?(user[:name]) }
626
+ step2_complete { |user| present?(user[:company]) }
627
+ step3_complete { |user| user[:preferences]&.any? }
628
+
629
+ can_proceed_to_step2 { |user| step1_complete(user) }
630
+ can_proceed_to_step3 { |user| step1_complete(user) && step2_complete(user) }
631
+ onboarding_complete { |user|
632
+ step1_complete(user) && step2_complete(user) && step3_complete(user)
633
+ }
634
+ end
635
+ ```
636
+
637
+ ### 2. Permission Checks
638
+
639
+ ```ruby
640
+ Predicate.define(:document) do
641
+ is_owner { |ctx| ctx[:document].user_id == ctx[:current_user].id }
642
+ is_admin { |ctx| ctx[:current_user].role == 'admin' }
643
+ is_public { |ctx| ctx[:document].visibility == 'public' }
644
+
645
+ can_view { |ctx| is_public(ctx) || is_owner(ctx) || is_admin(ctx) }
646
+ can_edit { |ctx| is_owner(ctx) || is_admin(ctx) }
647
+ can_delete { |ctx| is_owner(ctx) }
648
+ end
649
+ ```
650
+
651
+ ### 3. Business Rule Validation
652
+
653
+ ```ruby
654
+ Predicate.define(:order) do
655
+ has_items { |order| order[:items]&.any? }
656
+ has_shipping { |order| present?(order[:shipping_address]) }
657
+ has_payment { |order| present?(order[:payment_method_id]) }
658
+ above_minimum { |order| order[:total] >= 10.00 }
659
+
660
+ can_checkout { |order|
661
+ has_items(order) &&
662
+ has_shipping(order) &&
663
+ has_payment(order) &&
664
+ above_minimum(order)
665
+ }
666
+ end
667
+ ```
668
+
669
+ ### 4. Feature Flags
670
+
671
+ ```ruby
672
+ Predicate.define(:features) do
673
+ beta_user { |user| user[:beta_tester] == true }
674
+ paid_plan { |user| user[:subscription_plan] != 'free' }
675
+
676
+ show_advanced_features { |user| paid_plan(user) }
677
+ show_beta_features { |user| beta_user(user) }
678
+ show_export_button { |user| paid_plan(user) && user[:export_enabled] }
679
+ end
680
+ ```
681
+
682
+ ## ⚙️ Configuration
683
+
684
+ ### Global Settings
685
+
686
+ ```ruby
687
+ # Default cache size is 1000 entries
688
+ # TTL is optional (nil = no expiration)
689
+ # Thread-safety is opt-in (default: false)
690
+
691
+ # Per-entity configuration
692
+ Predicate.define(:fast_check, cache_ttl: 1.minute) { ... }
693
+ Predicate.define(:concurrent_check, thread_safe: true) { ... }
694
+ Predicate.define(:production, cache_ttl: 5.minutes, thread_safe: true) { ... }
695
+ ```
696
+
697
+ ### Cache Management
698
+
699
+ ```ruby
700
+ # Clear cache for specific entity
701
+ predicates = Predicate.for(:assessment)
702
+ predicates.clear_cache!
703
+
704
+ # Clear all caches across all entities
705
+ Predicate.clear_cache!
706
+
707
+ # Clear registry (remove all predicates)
708
+ Predicate.clear_registry!
709
+ ```
710
+
711
+ ## 🛠️ Troubleshooting
712
+
713
+ ### Cache Not Updating
714
+
715
+ ```ruby
716
+ # Force reload predicates from file
717
+ Assessment.load_predicates!(force_reload: true)
718
+
719
+ # Or clear cache manually
720
+ Predicate.for(:assessment).clear_cache!
721
+ ```
722
+
723
+ ### Predicate Not Found
724
+
725
+ ```ruby
726
+ # Check registered predicates
727
+ predicates = Predicate.for(:assessment)
728
+ predicates.predicate_names
729
+ # => [:has_title, :has_media, :wizard_complete]
730
+
731
+ # Check sections
732
+ predicates.section_names
733
+ # => [:validation, :permissions]
734
+ ```
735
+
736
+ ### Performance Issues
737
+
738
+ ```ruby
739
+ # Check cache hit rate
740
+ stats = predicates.cache_stats
741
+ hit_rate = stats[:cache_hit_ratio]
742
+
743
+ # Low hit rate? Consider increasing cache size or enabling TTL
744
+
745
+ # Check slow predicates
746
+ perf = predicates.performance_stats
747
+ slow_predicates = perf.select { |_, s| s[:average_time] > 0.01 }
748
+ ```
749
+
750
+ ## 🤝 Contributing
751
+
752
+ For bugs or feature requests, contact the development team.
753
+
754
+ ## 📄 License
755
+
756
+ Proprietary - StockLive Internal Use Only
757
+
758
+ ## 👤 Authors
759
+
760
+ Nauman Tariq - Initial design and implementation
761
+
762
+ ## 📌 Version
763
+
764
+ **1.0.0** - Initial Release (November 2025)