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.
@@ -0,0 +1,410 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Predicate
4
+ # Model Integration
5
+ #
6
+ # Auto-definition pattern for seamless model integration.
7
+ #
8
+ # Features::
9
+ # * Automatic predicate method generation
10
+ # * Inclusion helpers powered by `method_missing`
11
+ # * Predicate file auto-loading (`app/predicates/*_predicate.rb`)
12
+ # * Rails integration without requiring `ActiveSupport::Concern`
13
+ # * Lazy loading for better boot times
14
+ # * Cache invalidation helpers
15
+ # * Graceful error handling
16
+ #
17
+ # Usage::
18
+ # class Assessment < ApplicationRecord
19
+ # include Predicate::ModelIntegration
20
+ # # Auto-loads app/predicates/assessment_predicate.rb
21
+ # end
22
+ #
23
+ # assessment.has_media?
24
+ # assessment.wizard_complete?
25
+ #
26
+ # @author Nauman Tariq
27
+ # @version 1.0.0
28
+ module ModelIntegration
29
+ # Include class methods and auto-load predicates from app/predicates/.
30
+ # Models only need a single line: +include Predicate::ModelIntegration+
31
+ # The predicate file is resolved by convention from the model name
32
+ # (e.g. +LivestockType+ loads +app/predicates/livestock_type_predicate.rb+).
33
+ def self.included(base)
34
+ base.extend(ClassMethods)
35
+ base.load_predicates!
36
+ end
37
+
38
+ # CLASS METHODS
39
+ # Class-level methods for predicate management and configuration
40
+ module ClassMethods
41
+ # Get the predicate instance for this model
42
+ # @return [Predicate::Core, nil] The predicate instance or nil if not loaded
43
+ def predicate_instance
44
+ @predicate_instance
45
+ end
46
+
47
+ # Load predicates for this model
48
+ # @param force_reload [Boolean] Force reload even if already loaded
49
+ # @return [Predicate::Core] The loaded predicate instance
50
+ def load_predicates!(force_reload: false)
51
+ return @predicate_instance if @predicate_instance && !force_reload
52
+
53
+ # model_name may not be available during class definition
54
+ # (e.g. Class.new blocks where methods are defined after include).
55
+ # Predicates will be lazy-loaded on first use via method_missing.
56
+ return nil unless respond_to?(:model_name)
57
+
58
+ # Extract entity name flexibly from different model_name types
59
+ entity_name = extract_entity_name(model_name)
60
+
61
+ # Return nil if we couldn't determine entity name
62
+ return nil if entity_name.nil?
63
+
64
+ # If force_reload, try loading from file first to pick up changes
65
+ if force_reload
66
+ predicate_file = predicate_file_path(entity_name)
67
+
68
+ if File.exist?(predicate_file)
69
+ begin
70
+ # Clear registry entry to force fresh load
71
+ Registry.unregister(entity_name) if Registry.respond_to?(:unregister)
72
+
73
+ # Load the predicate file (will re-register)
74
+ load predicate_file
75
+ @predicate_instance = Predicate.for(entity_name)
76
+ return @predicate_instance
77
+ rescue StandardError => e
78
+ if defined?(Rails) && Rails.respond_to?(:logger)
79
+ Rails.logger.warn "Failed to reload predicates for #{entity_name}: #{e.message}"
80
+ end
81
+ # Fall through to registry check
82
+ end
83
+ end
84
+ end
85
+
86
+ # Check if predicates are already in the registry (for testing/programmatic usage)
87
+ begin
88
+ @predicate_instance = Predicate.for(entity_name)
89
+ return @predicate_instance
90
+ rescue KeyError
91
+ # Predicates not in registry, try loading from file
92
+ end
93
+
94
+ predicate_file = predicate_file_path(entity_name)
95
+
96
+ if File.exist?(predicate_file)
97
+ begin
98
+ # Load the predicate file
99
+ load predicate_file
100
+ @predicate_instance = Predicate.for(entity_name)
101
+ rescue StandardError => e
102
+ if defined?(Rails) && Rails.respond_to?(:logger)
103
+ Rails.logger.warn "Failed to load predicates for #{entity_name}: #{e.message}"
104
+ end
105
+ @predicate_instance = nil
106
+ end
107
+ else
108
+ if defined?(Rails) && Rails.respond_to?(:logger)
109
+ Rails.logger.debug { "No predicate file found for #{entity_name} at #{predicate_file}" }
110
+ end
111
+ @predicate_instance = nil
112
+ end
113
+
114
+ @predicate_instance
115
+ end
116
+
117
+ # Check if predicates are loaded for this model
118
+ # @return [Boolean] True if predicates are loaded
119
+ def predicates_loaded?
120
+ !@predicate_instance.nil?
121
+ end
122
+
123
+ # Clear cached predicates for this model
124
+ def clear_predicates!
125
+ @predicate_instance = nil
126
+ end
127
+
128
+ # Get all available predicate names for this model
129
+ # @return [Array<Symbol>] Array of predicate names
130
+ def predicate_names
131
+ load_predicates!
132
+ @predicate_instance&.predicate_names || []
133
+ end
134
+
135
+ # Check if a predicate exists for this model
136
+ # @param predicate_name [Symbol, String] The predicate name
137
+ # @return [Boolean] True if predicate exists
138
+ def predicate?(predicate_name)
139
+ load_predicates!
140
+ @predicate_instance&.predicate?(predicate_name) || false
141
+ end
142
+
143
+ private
144
+
145
+ # Extract entity name from different model_name types
146
+ # Handles Rails ActiveModel::Name, OpenStruct, String, Symbol, etc.
147
+ # @param model_name [Object] The model name object
148
+ # @return [Symbol, nil] The entity name as a symbol, or nil if invalid
149
+ # @example
150
+ # extract_entity_name(:user) # => :user
151
+ # extract_entity_name("User") # => :user
152
+ # extract_entity_name(User.model_name) # => :user (Rails)
153
+ # extract_entity_name(OpenStruct.new(underscore: 'user')) # => :user
154
+ def extract_entity_name(model_name)
155
+ return nil if model_name.nil?
156
+ return model_name if model_name.is_a?(Symbol)
157
+ return model_name.param_key.to_sym if model_name.respond_to?(:param_key)
158
+
159
+ if model_name.respond_to?(:underscore)
160
+ model_name.underscore.to_sym
161
+ else
162
+ # Use Util.underscore if ActiveSupport not available
163
+ Util.underscore(model_name.to_s).to_sym
164
+ end
165
+ end
166
+
167
+ # Get the predicate file path for a given entity
168
+ # @param entity_name [Symbol, String] The entity name
169
+ # @return [String] The full path to the predicate file
170
+ def predicate_file_path(entity_name)
171
+ if defined?(Rails) && Rails.respond_to?(:root)
172
+ Rails.root.join('app', 'predicates', "#{entity_name}_predicate.rb").to_s
173
+ else
174
+ File.join(Dir.pwd, 'app', 'predicates', "#{entity_name}_predicate.rb")
175
+ end
176
+ end
177
+ end
178
+
179
+ # INSTANCE METHODS
180
+ # Instance-level methods for predicate evaluation and model integration
181
+
182
+ # Get the predicate instance for this model instance
183
+ # @return [Predicate::Core, nil] The predicate instance or nil if not loaded
184
+ def predicate_instance
185
+ self.class.predicate_instance
186
+ end
187
+
188
+ # Load predicates for this model instance
189
+ # @return [Predicate::Core] The loaded predicate instance
190
+ def load_predicates!
191
+ self.class.load_predicates!
192
+ end
193
+
194
+ # Check if predicates are loaded for this model instance
195
+ # @return [Boolean] True if predicates are loaded
196
+ def predicates_loaded?
197
+ self.class.predicates_loaded?
198
+ end
199
+
200
+ # Get all available predicate names for this model instance
201
+ # @return [Array<Symbol>] Array of predicate names
202
+ def predicate_names
203
+ self.class.predicate_names
204
+ end
205
+
206
+ # Check if a predicate exists for this model instance
207
+ # @param predicate_name [Symbol, String] The predicate name
208
+ # @return [Boolean] True if predicate exists
209
+ def predicate?(predicate_name)
210
+ self.class.predicate?(predicate_name)
211
+ end
212
+
213
+ # Call a predicate with this instance's state
214
+ # @param predicate_name [Symbol, String] The predicate name
215
+ # @param additional_state [Hash] Additional state to merge
216
+ # @return [Boolean] The predicate result
217
+ def call_predicate(predicate_name, additional_state = {})
218
+ return false unless predicates_loaded?
219
+
220
+ predicate_instance = self.class.predicate_instance
221
+ return false unless predicate_instance
222
+
223
+ state = build_state_hash(additional_state)
224
+ predicate_instance.call(predicate_name, state)
225
+ end
226
+
227
+ # Get predicate statistics for this instance
228
+ # @return [Hash] Predicate performance statistics
229
+ def predicate_stats
230
+ load_predicates!
231
+ predicate_instance = self.class.predicate_instance
232
+ predicate_instance&.performance_stats || {}
233
+ end
234
+
235
+ # Clear predicate cache for this instance
236
+ def clear_predicate_cache!
237
+ load_predicates!
238
+ predicate_instance = self.class.predicate_instance
239
+ predicate_instance&.clear_cache!
240
+ end
241
+
242
+ # Handle missing predicate methods
243
+ # @param method_name [Symbol] The method name
244
+ # @param args [Array] Method arguments
245
+ # @return [Boolean] The predicate result
246
+ def method_missing(method_name, *args)
247
+ # Check if this looks like a predicate method (ends with ?)
248
+ if method_name.to_s.end_with?('?') && args.empty?
249
+ predicate_name = method_name.to_s.chomp('?').to_sym
250
+
251
+ # Lazy-load predicates on first use if not yet loaded
252
+ load_predicates! unless predicates_loaded?
253
+
254
+ # Only try to call if predicates are loaded and predicate exists
255
+ if predicates_loaded? && predicate?(predicate_name)
256
+ call_predicate(predicate_name)
257
+ else
258
+ # Predicate doesn't exist or not loaded, return false for predicate methods
259
+ false
260
+ end
261
+ else
262
+ # Not a predicate method, call super
263
+ super
264
+ end
265
+ end
266
+
267
+ # Check if this instance responds to a method
268
+ # @param method_name [Symbol] The method name
269
+ # @param include_private [Boolean] Include private methods
270
+ # @return [Boolean] True if responds to method
271
+ def respond_to_missing?(method_name, include_private = false)
272
+ # Check if this looks like a predicate method
273
+ if method_name.to_s.end_with?('?')
274
+ predicate_name = method_name.to_s.chomp('?').to_sym
275
+ # Only return true if predicates are loaded AND the predicate exists
276
+ return predicate?(predicate_name) if predicates_loaded?
277
+
278
+ return false
279
+
280
+ end
281
+
282
+ super
283
+ end
284
+
285
+ private
286
+
287
+ # Build a state hash from this instance's attributes
288
+ # @param additional_state [Hash] Additional state to merge
289
+ # @return [Hash] The complete state hash
290
+ def build_state_hash(additional_state = {})
291
+ # Start with attributes if available
292
+ state = extract_base_state
293
+
294
+ # Stringify keys for consistency then symbolize
295
+ # This handles both string and symbol keys in attributes
296
+ state = state.transform_keys(&:to_sym)
297
+
298
+ # Merge additional state
299
+ state.merge!(additional_state) if additional_state
300
+
301
+ state
302
+ end
303
+
304
+ def extract_base_state
305
+ if respond_to?(:attributes) && attributes.is_a?(Hash)
306
+ base_state = attributes.dup
307
+ Rails.logger.debug { "DEBUG: Model attributes: #{base_state.inspect}" } if defined?(Rails) && Rails.respond_to?(:logger)
308
+ base_state
309
+ elsif respond_to?(:to_h)
310
+ base_state = to_h.dup
311
+ Rails.logger.debug { "DEBUG: Model to_h: #{base_state.inspect}" } if defined?(Rails) && Rails.respond_to?(:logger)
312
+ base_state
313
+ else
314
+ # Fallback to instance variables
315
+ base_state = instance_variables.each_with_object({}) do |var, hash|
316
+ hash[var.to_s.delete('@').to_sym] = instance_variable_get(var)
317
+ end
318
+ Rails.logger.debug { "DEBUG: Model instance variables: #{base_state.inspect}" } if defined?(Rails) && Rails.respond_to?(:logger)
319
+ base_state
320
+ end
321
+ end
322
+
323
+ # PREDICATE FILE GENERATOR
324
+ # Utility for generating predicate files from model analysis
325
+ module PredicateFileGenerator
326
+ # Generate a predicate file for a model
327
+ # @param model_class [Class] The model class
328
+ # @param output_path [String] The output path (optional)
329
+ # @return [String] The generated predicate file content
330
+ def self.generate_for_model(model_class, output_path = nil)
331
+ # Use ActiveSupport::Inflector if available, otherwise basic conversion
332
+ entity_name = if model_class.name.respond_to?(:underscore)
333
+ model_class.name.underscore.to_sym
334
+ else
335
+ # Try to require ActiveSupport, fall back to basic conversion
336
+ # if not available
337
+ begin
338
+ require 'active_support/inflector'
339
+ ActiveSupport::Inflector.underscore(model_class.name).to_sym
340
+ rescue LoadError
341
+ # Basic snake_case conversion without ActiveSupport
342
+ Util.underscore(model_class.name).to_sym
343
+ end
344
+ end
345
+
346
+ predicate_content = generate_predicate_content(model_class, entity_name)
347
+
348
+ if output_path
349
+ File.write(output_path, predicate_content)
350
+ # Only log if Rails is available
351
+ if defined?(Rails) && Rails.respond_to?(:logger)
352
+ Rails.logger.debug { "Generated predicate file: #{output_path}" }
353
+ end
354
+ end
355
+
356
+ predicate_content
357
+ end
358
+
359
+ # Generate predicate content based on model analysis
360
+ # @param model_class [Class] The model class
361
+ # @param entity_name [Symbol] The entity name
362
+ # @return [String] The generated predicate content
363
+ def self.generate_predicate_content(model_class, entity_name)
364
+ content = []
365
+ content << '# frozen_string_literal: true'
366
+ content << ''
367
+ content << "# Auto-generated predicate file for #{model_class.name}"
368
+ # Use Time.now if Time.zone not available
369
+ timestamp = Predicate::Util.now
370
+ content << "# Generated on: #{timestamp}"
371
+ content << ''
372
+ content << "Predicate.define(:#{entity_name}) do"
373
+ content << ' # TODO: Add your predicates here'
374
+ content << ' # Example predicates based on model analysis:'
375
+ content << ''
376
+
377
+ content += generate_attribute_predicates(model_class)
378
+ content += generate_association_predicates(model_class)
379
+
380
+ content << ' # Add custom predicates below:'
381
+ content << ' # wizard_complete { |s| has_title(s) && has_description(s) }'
382
+ content << 'end'
383
+ content << ''
384
+
385
+ content.join("\n")
386
+ end
387
+
388
+ def self.generate_attribute_predicates(model_class)
389
+ return [] unless model_class.respond_to?(:attribute_names)
390
+
391
+ model_class.attribute_names.map do |attr|
392
+ next if %w[id created_at updated_at].include?(attr.to_s)
393
+
394
+ " has_#{attr} { |s| is_present?(s[:#{attr}]) }"
395
+ end.compact
396
+ end
397
+
398
+ def self.generate_association_predicates(model_class)
399
+ return [] unless model_class.respond_to?(:reflect_on_all_associations)
400
+
401
+ model_class.reflect_on_all_associations.map do |assoc|
402
+ " has_#{assoc.name} { |s| is_present?(s[:#{assoc.name}]) }"
403
+ end
404
+ end
405
+ end
406
+
407
+ # Include the generator in the main module
408
+ extend PredicateFileGenerator
409
+ end
410
+ end
@@ -0,0 +1,19 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Predicate
4
+ class Railtie < Rails::Railtie
5
+ initializer 'predicate.configure_autoloading' do
6
+ predicates_path = Rails.root.join('app', 'predicates')
7
+ if Dir.exist?(predicates_path)
8
+ # Predicate files register entries via Predicate.define — they don't
9
+ # define Ruby constants. Tell Zeitwerk to skip them.
10
+ # Loading is handled by ModelIntegration.load_predicates! via Kernel#load.
11
+ Rails.autoloaders.main.ignore(predicates_path)
12
+ end
13
+ end
14
+
15
+ config.to_prepare do
16
+ Predicate.clear_registry! if Rails.env.development?
17
+ end
18
+ end
19
+ end
@@ -0,0 +1,36 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Predicate
4
+ # General Utility Methods
5
+ module Util
6
+ module_function
7
+
8
+ # Basic underscore conversion for class names (without ActiveSupport)
9
+ # @param class_name [String] The class name to convert
10
+ # @return [String] The underscored version
11
+ # @example
12
+ # underscore("UserAccount") # => "user_account"
13
+ # underscore("API") # => "api"
14
+ def underscore(class_name)
15
+ return class_name unless class_name
16
+
17
+ name = class_name.to_s.dup
18
+ # Replace :: with /
19
+ name.gsub!('::', '/')
20
+ # Insert underscore before uppercase letters that follow lowercase letters
21
+ name.gsub!(/([a-z\d])([A-Z])/, '\1_\2')
22
+ # Insert underscore before uppercase letters that are followed by lowercase letters
23
+ name.gsub!(/([A-Z]+)([A-Z][a-z])/, '\1_\2')
24
+ # Convert to lowercase
25
+ name.downcase
26
+ end
27
+
28
+ # Get current time
29
+ # @return [Time, ActiveSupport::TimeWithZone] Current time
30
+ def now
31
+ return ::Time.zone.now if defined?(::Time.zone) && ::Time.zone
32
+
33
+ ::Time.now
34
+ end
35
+ end
36
+ end