Module: Familia::Horreum::ClassMethods
- Includes:
- RelatedFieldsManagement, Settings
- Defined in:
- lib/familia/horreum/class_methods.rb
Overview
ClassMethods: Provides class-level functionality for Horreum
This module is extended into classes that include Familia::Horreum, providing methods for Database operations and object management.
Key features: * Includes RelatedFieldsManagement for DataType field handling * Defines methods for managing fields, identifiers, and dbkeys * Provides utility methods for working with Database objects
Instance Attribute Summary
Attributes included from Settings
Instance Method Summary collapse
-
#all(suffix = nil) ⇒ Object
-
#any?(filter = '*') ⇒ Boolean
-
#class_related_fields ⇒ Object
-
#config_name ⇒ String
Converts the class name into a string that can be used to look up configuration values.
-
#create ⇒ Object
Creates and persists a new instance of the class.
-
#dbkey(identifier, suffix = self.suffix) ⇒ Object
+identifier+ can be a value or an Array of values used to create the index.
-
#destroy!(identifier, suffix = nil) ⇒ Boolean
Destroys an object in Database with the given identifier.
-
#dump_method ⇒ Object
-
#exists?(identifier, suffix = nil) ⇒ Boolean
Checks if an object with the given identifier exists in Redis.
-
#fast_attribute!(name = nil) ⇒ Object
Defines a fast attribute method with a bang (!) suffix for a given attribute name.
-
#field(name) ⇒ Object
Defines a field for the class and creates accessor methods.
-
#fields ⇒ Object
Returns the list of field names defined for the class in the order that they were defined.
-
#find_by_id(identifier, suffix = nil) ⇒ Object?
(also: #find, #load, #from_identifier)
Retrieves and instantiates an object from Database using its identifier.
-
#find_by_key(objkey) ⇒ Object?
(also: #from_dbkey)
Retrieves and instantiates an object from Database using the full object key.
-
#find_keys(suffix = '*') ⇒ Array<String>
Finds all keys in Database matching the given suffix pattern.
-
#has_relations? ⇒ Boolean
-
#identifier_field(val = nil) ⇒ Object
Sets or retrieves the unique identifier field for the class.
-
#load_method ⇒ Object
-
#logical_database(v = nil) ⇒ Object
-
#matching_keys_count(filter = '*') ⇒ Integer
(also: #size)
Returns the number of dbkeys matching the given filter pattern.
-
#multiget(*ids) ⇒ Object
-
#prefix(a = nil) ⇒ String, Symbol
Sets or retrieves the prefix for generating Redis keys.
-
#rawmultiget(*ids) ⇒ Object
-
#related_fields ⇒ Object
-
#suffix(a = nil, &blk) ⇒ Object
Methods included from RelatedFieldsManagement
#attach_class_related_field, #attach_instance_related_field
Methods included from Settings
Instance Method Details
#all(suffix = nil) ⇒ Object
197 198 199 200 201 |
# File 'lib/familia/horreum/class_methods.rb', line 197 def all(suffix = nil) suffix ||= self.suffix # objects that could not be parsed will be nil keys(suffix).filter_map { |k| find_by_key(k) } end |
#any?(filter = '*') ⇒ Boolean
203 204 205 |
# File 'lib/familia/horreum/class_methods.rb', line 203 def any?(filter = '*') matching_keys_count(filter) > 0 end |
#class_related_fields ⇒ Object
177 178 179 180 |
# File 'lib/familia/horreum/class_methods.rb', line 177 def @class_related_fields ||= {} @class_related_fields end |
#config_name ⇒ String
Converts the class name into a string that can be used to look up configuration values. This is particularly useful when mapping familia models with specific database numbers in the configuration.
247 248 249 250 251 252 |
# File 'lib/familia/horreum/class_methods.rb', line 247 def config_name name.split('::').last .gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2') .gsub(/([a-z\d])([A-Z])/, '\1_\2') .downcase end |
#create ⇒ Object
The behavior of this method depends on the implementation of #new, #exists?, and #save in the class and its superclasses.
Creates and persists a new instance of the class.
This method serves as a factory method for creating and persisting new instances of the class. It combines object instantiation, existence checking, and persistence in a single operation.
The method is flexible in accepting both positional and keyword arguments: - Positional arguments (*args) are passed directly to the constructor. - Keyword arguments (**kwargs) are passed as a hash to the constructor.
After instantiation, the method checks if an object with the same identifier already exists. If it does, a Familia::Problem exception is raised to prevent overwriting existing data.
Finally, the method saves the new instance returns it.
290 291 292 293 294 295 296 |
# File 'lib/familia/horreum/class_methods.rb', line 290 def create(*, **) fobj = new(*, **) raise Familia::Problem, "#{self} already exists: #{fobj.dbkey}" if fobj.exists? fobj.save fobj end |
#dbkey(identifier, suffix = self.suffix) ⇒ Object
+identifier+ can be a value or an Array of values used to create the index. We don’t enforce a default suffix; that’s left up to the instance. The suffix is used to differentiate between different types of objects.
+suffix+ If a nil value is explicitly passed in, it won’t appear in the redis key that’s returned. If no suffix is passed in, the class’ suffix is used as the default (via the class method self.suffix). It’s an important distinction b/c passing in an explicitly nil is how DataType objects at the class level are created without the global default ‘object’ suffix. See DataType#dbkey “parent_class?” for more details.
471 472 473 474 475 476 477 |
# File 'lib/familia/horreum/class_methods.rb', line 471 def dbkey(identifier, suffix = self.suffix) # Familia.ld "[.dbkey] #{identifier} for #{self} (suffix:#{suffix})" raise NoIdentifier, self if identifier.to_s.empty? identifier &&= identifier.to_s Familia.dbkey(prefix, identifier, suffix) end |
#destroy!(identifier, suffix = nil) ⇒ Boolean
Destroys an object in Database with the given identifier.
This method is part of Familia’s high-level object lifecycle management. While delete!
operates directly on dbkeys, destroy! operates at the object level and is used for
ORM-style operations. Use destroy! when removing complete objects from the system, and
delete! when working directly with dbkeys.
434 435 436 437 438 439 440 441 442 443 |
# File 'lib/familia/horreum/class_methods.rb', line 434 def destroy!(identifier, suffix = nil) suffix ||= self.suffix return false if identifier.to_s.empty? objkey = dbkey identifier, suffix ret = dbclient.del objkey Familia.trace :DESTROY!, dbclient, "#{objkey} #{ret.inspect}", caller(1..1) if Familia.debug? ret.positive? end |
#dump_method ⇒ Object
479 480 481 |
# File 'lib/familia/horreum/class_methods.rb', line 479 def dump_method @dump_method || :to_json # Familia.dump_method end |
#exists?(identifier, suffix = nil) ⇒ Boolean
Checks if an object with the given identifier exists in Redis.
This method constructs the full dbkey using the provided identifier and suffix, then checks if the key exists in Redis.
408 409 410 411 412 413 414 415 416 417 418 |
# File 'lib/familia/horreum/class_methods.rb', line 408 def exists?(identifier, suffix = nil) suffix ||= self.suffix return false if identifier.to_s.empty? objkey = dbkey identifier, suffix ret = dbclient.exists objkey Familia.trace :EXISTS, dbclient, "#{objkey} #{ret.inspect}", caller(1..1) if Familia.debug? ret.positive? # differs from Valkey API but I think it's okay bc `exists?` is a predicate method. end |
#fast_attribute!(name = nil) ⇒ Object
Defines a fast attribute method with a bang (!) suffix for a given attribute name. Fast attribute methods are used to immediately read or write attribute values from/to Redis. Calling a fast attribute method has no effect on any of the object’s other attributes and does not trigger a call to update the object’s expiration time.
The dynamically defined method performs the following: - Acts as both a reader and a writer method. - When called without arguments, retrieves the current value from Redis. - When called with an argument, persists the value to Database immediately. - Checks if the correct number of arguments is provided (zero or one). - Converts the provided value to a format suitable for Database storage. - Uses the existing accessor method to set the attribute value when writing. - Persists the value to Database immediately using the hset command when writing. - Includes custom error handling to raise an ArgumentError if the wrong number of arguments is given. - Raises a custom error message if an exception occurs during the execution of the method.
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 |
# File 'lib/familia/horreum/class_methods.rb', line 106 def fast_attribute!(name = nil) # Fast attribute accessor method for the '#{name}' attribute. # This method provides immediate read and write access to the attribute # in Redis. # # When called without arguments, it retrieves the current value of the # attribute from Redis. # When called with an argument, it immediately persists the new value to # Redis. # # @overload #{name}! # Retrieves the current value of the attribute from Redis. # @return [Object] the current value of the attribute. # # @overload #{name}!(value) # Sets and immediately persists the new value of the attribute to # Redis. # @param value [Object] the new value to set for the attribute. # @return [Object] the newly set value. # # @raise [ArgumentError] if more than one argument is provided. # @raise [RuntimeError] if an exception occurs during the execution of # the method. # # @note This method bypasses any object-level caching and interacts # directly with Redis. It does not trigger updates to other attributes # or the object's expiration time. # # @example # # def #{name}!(*args) # # Method implementation # end # define_method :"#{name}!" do |*args| # Check if the correct number of arguments is provided (exactly one). raise ArgumentError, "wrong number of arguments (given #{args.size}, expected 0 or 1)" if args.size > 1 val = args.first # If no value is provided to this fast attribute method, make a call # to the db to return the current stored value of the hash field. return hget name if val.nil? begin # Trace the operation if debugging is enabled. Familia.trace :FAST_WRITER, dbclient, "#{name}: #{val.inspect}", caller(1..1) if Familia.debug? # Convert the provided value to a format suitable for Database storage. prepared = serialize_value(val) Familia.ld "[.fast_attribute!] #{name} val: #{val.class} prepared: #{prepared.class}" # Use the existing accessor method to set the attribute value. send :"#{name}=", val # Persist the value to Database immediately using the hset command. hset name, prepared rescue Familia::Problem => e # Raise a custom error message if an exception occurs during the execution of the method. raise "#{name}! method failed: #{e.}", e.backtrace end end end |
#field(name) ⇒ Object
Defines a field for the class and creates accessor methods.
This method defines a new field for the class, creating getter and setter
instance methods similar to attr_accessor. It also generates a fast
writer method for immediate persistence to Redis.
69 70 71 72 73 74 75 |
# File 'lib/familia/horreum/class_methods.rb', line 69 def field(name) fields << name attr_accessor name # Every field gets a fast attribute method for immediately persisting fast_attribute! name end |
#fields ⇒ Object
Returns the list of field names defined for the class in the order
that they were defined. i.e. field :a; field :b; fields => [:a, :b].
172 173 174 175 |
# File 'lib/familia/horreum/class_methods.rb', line 172 def fields @fields ||= [] @fields end |
#find_by_id(identifier, suffix = nil) ⇒ Object? Also known as: find, load, from_identifier
Retrieves and instantiates an object from Database using its identifier.
This method constructs the full dbkey using the provided identifier
and suffix, then delegates to find_by_key for the actual retrieval and
instantiation.
It’s a higher-level method that abstracts away the key construction, making it easier to retrieve objects when you only have their identifier.
382 383 384 385 386 387 388 389 390 391 |
# File 'lib/familia/horreum/class_methods.rb', line 382 def find_by_id(identifier, suffix = nil) suffix ||= self.suffix return nil if identifier.to_s.empty? objkey = dbkey(identifier, suffix) Familia.ld "[.find_by_id] #{self} from key #{objkey})" Familia.trace :FIND_BY_ID, Familia.dbclient(uri), objkey, caller(1..1).first if Familia.debug? find_by_key objkey end |
#find_by_key(objkey) ⇒ Object? Also known as: from_dbkey
Retrieves and instantiates an object from Database using the full object key.
This method performs a two-step process to safely retrieve and instantiate objects:
- It first checks if the key exists in Redis. This is crucial because:
- It provides a definitive answer about the object’s existence.
- It prevents ambiguity that could arise from
hgetallreturning an empty hash for non-existent keys, which could lead to the creation of “empty” objects.
- If the key exists, it retrieves the object’s data and instantiates it.
This approach ensures that we only attempt to instantiate objects that actually exist in Redis, improving reliability and simplifying debugging.
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 |
# File 'lib/familia/horreum/class_methods.rb', line 339 def find_by_key(objkey) raise ArgumentError, 'Empty key' if objkey.to_s.empty? # We use a lower-level method here b/c we're working with the # full key and not just the identifier. does_exist = dbclient.exists(objkey).positive? Familia.ld "[.find_by_key] #{self} from key #{objkey} (exists: #{does_exist})" Familia.trace :FROM_KEY, dbclient, objkey, caller(1..1) if Familia.debug? # This is the reason for calling exists first. We want to definitively # and without any ambiguity know if the object exists in Redis. If it # doesn't, we return nil. If it does, we proceed to load the object. # Otherwise, hgetall will return an empty hash, which will be passed to # the constructor, which will then be annoying to debug. return unless does_exist obj = dbclient.hgetall(objkey) # horreum objects are persisted as database hashes Familia.trace :FROM_KEY2, dbclient, "#{objkey}: #{obj.inspect}", caller(1..1) if Familia.debug? new(**obj) end |
#find_keys(suffix = '*') ⇒ Array<String>
Finds all keys in Database matching the given suffix pattern.
This method searches for all dbkeys that match the given suffix pattern. It uses the class’s dbkey method to construct the search pattern.
457 458 459 |
# File 'lib/familia/horreum/class_methods.rb', line 457 def find_keys(suffix = '*') dbclient.keys(dbkey('*', suffix)) || [] end |
#has_relations? ⇒ Boolean
187 188 189 |
# File 'lib/familia/horreum/class_methods.rb', line 187 def has_relations? @has_relations ||= false end |
#identifier_field(val = nil) ⇒ Object
Sets or retrieves the unique identifier field for the class.
This method defines or returns the field or method that contains the unique identifier used to generate the dbkey for the object. If a value is provided, it sets the identifier field; otherwise, it returns the current identifier field.
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
# File 'lib/familia/horreum/class_methods.rb', line 45 def identifier_field(val = nil) if val # Validate identifier field definition at class definition time case val when Symbol, String, Proc @identifier_field = val else raise Problem, <<~ERROR Invalid identifier field definition: #{val.inspect}. Use a field name (Symbol/String) or Proc. ERROR end end @identifier_field end |
#load_method ⇒ Object
483 484 485 |
# File 'lib/familia/horreum/class_methods.rb', line 483 def load_method @load_method || :from_json # Familia.load_method end |
#logical_database(v = nil) ⇒ Object
191 192 193 194 195 |
# File 'lib/familia/horreum/class_methods.rb', line 191 def logical_database(v = nil) Familia.trace :DB, Familia.dbclient, "#{@logical_database} #{v}", caller(1..1) if Familia.debug? @logical_database = v unless v.nil? @logical_database || parent&.logical_database end |
#matching_keys_count(filter = '*') ⇒ Integer Also known as: size
Returns the number of dbkeys matching the given filter pattern
210 211 212 |
# File 'lib/familia/horreum/class_methods.rb', line 210 def matching_keys_count(filter = '*') dbclient.keys(dbkey(filter)).compact.size end |
#multiget(*ids) ⇒ Object
298 299 300 301 |
# File 'lib/familia/horreum/class_methods.rb', line 298 def multiget(*ids) ids = rawmultiget(*ids) ids.filter_map { |json| from_json(json) } end |
#prefix(a = nil) ⇒ String, Symbol
Sets or retrieves the prefix for generating Redis keys.
The exception is only raised when both @prefix is nil/falsy AND name is nil, which typically occurs with anonymous classes that haven’t had their prefix explicitly set.
229 230 231 232 233 234 235 236 237 238 |
# File 'lib/familia/horreum/class_methods.rb', line 229 def prefix(a = nil) @prefix = a if a @prefix || begin if name.nil? raise Problem, 'Cannot generate prefix for anonymous class. ' \ 'Use `prefix` method to set explicitly.' end name.downcase.gsub('::', Familia.delim).to_sym end end |
#rawmultiget(*ids) ⇒ Object
303 304 305 306 307 308 309 |
# File 'lib/familia/horreum/class_methods.rb', line 303 def rawmultiget(*ids) ids.collect! { |objid| dbkey(objid) } return [] if ids.compact.empty? Familia.trace :MULTIGET, dbclient, "#{ids.size}: #{ids}", caller(1..1) if Familia.debug? dbclient.mget(*ids) end |
#related_fields ⇒ Object
182 183 184 185 |
# File 'lib/familia/horreum/class_methods.rb', line 182 def @related_fields ||= {} @related_fields end |
#suffix(a = nil, &blk) ⇒ Object
215 216 217 218 |
# File 'lib/familia/horreum/class_methods.rb', line 215 def suffix(a = nil, &blk) @suffix = a || blk if a || !blk.nil? @suffix || Familia.default_suffix end |