Class: Familia::Horreum
- Inherits:
-
Object
- Object
- Familia::Horreum
- Defined in:
- lib/familia/horreum.rb,
lib/familia/horreum/core.rb,
lib/familia/horreum/core/utils.rb,
lib/familia/horreum/core/connection.rb,
lib/familia/horreum/shared/settings.rb,
lib/familia/horreum/core/serialization.rb,
lib/familia/horreum/subclass/definition.rb,
lib/familia/horreum/subclass/management.rb,
lib/familia/horreum/core/database_commands.rb,
lib/familia/horreum/subclass/related_fields_management.rb
Overview
Familia::Horreum
This module is included in classes that include Familia, providing instance-level functionality for Database operations and object management.
Defined Under Namespace
Modules: Connection, Core, DatabaseCommands, DefinitionMethods, ManagementMethods, RelatedFieldsManagement, Serialization, Settings, Utils
Constant Summary collapse
- ParentDefinition =
Each related field needs some details from the parent (Horreum model) in order to generate its dbkey. We use a parent proxy pattern to store only essential parent information instead of full object reference. We need only the model class and an optional unique identifier to generate the dbkey; when the identifier is nil, we treat this as a class-level relation (e.g. model_name:related_field_name); when the identifier is not nil, we treat this as an instance-level relation (model_name:identifier:related_field_name).
Data.define(:model_klass, :identifier) do # Factory method to create ParentDefinition from a parent instance def self.from_parent(parent_instance) case parent_instance when Class # Handle class-level relationships new(parent_instance, nil) else # Handle instance-level relationships identifier = parent_instance.respond_to?(:identifier) ? parent_instance.identifier : nil new(parent_instance.class, identifier) end end # Delegation methods for common operations needed by DataTypes def dbclient(uri = nil) model_klass.dbclient(uri) end def logical_database model_klass.logical_database end def dbkey(keystring = nil) if identifier # Instance-level relation: model_name:identifier:keystring model_klass.dbkey(identifier, keystring) else # Class-level relation: model_name:keystring model_klass.dbkey(keystring, nil) end end # Allow comparison with the original parent instance def ==(other) case other when ParentDefinition model_klass == other.model_klass && identifier == other.identifier when Class model_klass == other && identifier.nil? else # Compare with instance: check class and identifier match other.is_a?(model_klass) && other.respond_to?(:identifier) && identifier == other.identifier end end alias eql? == end
Class Attribute Summary collapse
-
.dbclient ⇒ Object
writeonly
TODO: Where are we calling dbclient= from now with connection pool?.
-
.dump_method ⇒ Object
writeonly
TODO: Where are we calling dbclient= from now with connection pool?.
-
.has_related_fields ⇒ Object
readonly
Returns the value of attribute has_related_fields.
-
.load_method ⇒ Object
writeonly
TODO: Where are we calling dbclient= from now with connection pool?.
-
.parent ⇒ Object
Returns the value of attribute parent.
-
.valid_command_return_values ⇒ Object
readonly
Returns the value of attribute valid_command_return_values.
Instance Attribute Summary collapse
-
#dbclient ⇒ Object
writeonly
Sets the attribute dbclient.
Attributes included from Settings
#dump_method, #load_method, #suffix
Attributes included from Connection
Class Method Summary collapse
-
.inherited(member) ⇒ Object
Extends ClassMethods to subclasses and tracks Familia members.
Instance Method Summary collapse
- #generate_id ⇒ Object
-
#identifier ⇒ Object
Determines the unique identifier for the instance This method is used to generate dbkeys for the object Returns nil for unsaved objects (following standard ORM patterns).
- #init(*args, **kwargs) ⇒ Object
-
#initialize(*args, **kwargs) ⇒ Horreum
constructor
Instance initialization This method sets up the object's state, including Valkey/Redis-related data.
-
#initialize_relatives ⇒ Object
Sets up related Database objects for the instance This method is crucial for establishing Valkey/Redis-based relationships.
- #initialize_with_keyword_args_deserialize_value(**fields) ⇒ Object
-
#optimistic_refresh(**fields) ⇒ Array
A thin wrapper around the private initialize method that accepts a field hash and refreshes the existing object.
-
#to_s ⇒ Object
The principle is: If Familia objects have
to_s, then they should work everywhere strings are expected, including as Database hash field names.
Methods included from Settings
#logical_database, #logical_database=, #opts, #prefix
Methods included from Utils
Methods included from Connection
#connect, #create_dbclient, #dbclient, #normalize_uri, #pipelined, #transaction
Methods included from Serialization
#apply_fields, #batch_update, #clear_fields!, #commit_fields, #deserialize_value, #destroy!, #refresh, #refresh!, #save, #save_if_not_exists, #serialize_value, #to_a, #to_h, #to_h_for_storage
Methods included from DatabaseCommands
#current_expiration, #data_type, #decr, #decrby, #delete!, #echo, #exists?, #expire, #field_count, #hget, #hgetall, #hkeys, #hmset, #hset, #hsetnx, #hstrlen, #hvals, #incr, #incrby, #incrbyfloat, #key?, #move, #remove_field
Methods included from Base
add_feature, #as_json, #expired?, #expires?, find_feature, #to_json, #ttl, #update_expiration, #uuid
Constructor Details
#initialize(*args, **kwargs) ⇒ Horreum
Instance initialization This method sets up the object's state, including Valkey/Redis-related data.
Usage:
Session.new("abc123", "user456") # positional (brittle)
Session.new(sessid: "abc123", custid: "user456") # hash (robust)
Session.new({sessid: "abc123", custid: "user456"}) # legacy hash (robust)
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 |
# File 'lib/familia/horreum.rb', line 180 def initialize(*args, **kwargs) Familia.trace :INITIALIZE, nil, "Initializing #{self.class}" if Familia.debug? initialize_relatives # No longer auto-create a key field - the identifier method will # directly use the field specified by identifier_field # Detect if first argument is a hash (legacy support) if args.size == 1 && args.first.is_a?(Hash) && kwargs.empty? kwargs = args.first args = [] end # Initialize object with arguments using one of four strategies: # # 1. **Identifier** (Recommended for lookups): A single argument is # treated as the identifier. Robust and convenient for creating # objects from an ID. e.g. `Customer.new("cust_123")` # # 2. **Keyword Arguments** (Recommended for creation): Order-independent # field assignment # e.g. Customer.new(name: "John", email: "john@example.com") # # 3. **Positional Arguments** (Legacy): Field assignment by definition order # e.g. Customer.new("cust_123", "John", "john@example.com") # # 4. **No Arguments**: Object created with all fields as nil # if args.size == 1 && kwargs.empty? id_field = self.class.identifier_field send(:"#{id_field}=", args.first) elsif kwargs.any? initialize_with_keyword_args(**kwargs) elsif args.any? initialize_with_positional_args(*args) elsif Familia.debug? Familia.trace :INITIALIZE, nil, "#{self.class} initialized with no arguments" # Default values are intentionally NOT set here end # Implementing classes can define an init method to do any # additional initialization. Notice that this is called # after the fields are set. init end |
Class Attribute Details
.dbclient=(value) ⇒ Object (writeonly)
TODO: Where are we calling dbclient= from now with connection pool?
79 80 81 |
# File 'lib/familia/horreum.rb', line 79 def dbclient=(value) @dbclient = value end |
.dump_method=(value) ⇒ Object (writeonly)
TODO: Where are we calling dbclient= from now with connection pool?
79 80 81 |
# File 'lib/familia/horreum.rb', line 79 def dump_method=(value) @dump_method = value end |
.has_related_fields ⇒ Object (readonly)
Returns the value of attribute has_related_fields.
80 81 82 |
# File 'lib/familia/horreum.rb', line 80 def @has_related_fields end |
.load_method=(value) ⇒ Object (writeonly)
TODO: Where are we calling dbclient= from now with connection pool?
79 80 81 |
# File 'lib/familia/horreum.rb', line 79 def load_method=(value) @load_method = value end |
.parent ⇒ Object
Returns the value of attribute parent.
77 78 79 |
# File 'lib/familia/horreum.rb', line 77 def parent @parent end |
.valid_command_return_values ⇒ Object (readonly)
Returns the value of attribute valid_command_return_values.
31 32 33 |
# File 'lib/familia/horreum/core/serialization.rb', line 31 def valid_command_return_values @valid_command_return_values end |
Instance Attribute Details
#dbclient=(value) ⇒ Object (writeonly)
Sets the attribute dbclient
169 170 171 |
# File 'lib/familia/horreum.rb', line 169 def dbclient=(value) @dbclient = value end |
Class Method Details
.inherited(member) ⇒ Object
Extends ClassMethods to subclasses and tracks Familia members
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 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 |
# File 'lib/familia/horreum.rb', line 83 def inherited(member) Familia.trace :HORREUM, nil, "Welcome #{member} to the family" if Familia.debug? # Class-level functionality extensions: member.extend(Familia::Horreum::DefinitionMethods) # field(), identifier_field(), dbkey() member.extend(Familia::Horreum::ManagementMethods) # create(), find(), destroy!() member.extend(Familia::Horreum::Connection) # dbclient, connection management member.extend(Familia::Features) # feature() method for optional modules # Copy parent class configuration to child class # This implements conventional ORM inheritance behavior where child classes # automatically inherit all parent configuration without manual copying parent_class = member.superclass if parent_class.respond_to?(:identifier_field) && parent_class != Familia::Horreum # Copy essential configuration instance variables from parent if parent_class.identifier_field member.instance_variable_set(:@identifier_field, parent_class.identifier_field) end # Copy field system configuration member.instance_variable_set(:@fields, parent_class.fields.dup) if parent_class.fields&.any? if parent_class.respond_to?(:field_types) && parent_class.field_types&.any? # Copy field_types hash (FieldType instances are frozen/immutable and can be safely shared) copied_field_types = parent_class.field_types.dup member.instance_variable_set(:@field_types, copied_field_types) # Re-install field methods on the child class using proper method name detection parent_class.field_types.each_value do |field_type| # Collect all method names that field_type.install will create methods_to_check = [ field_type.method_name, (field_type.method_name ? :"#{field_type.method_name}=" : nil), field_type.fast_method_name, ].compact # Only install if none of the methods already exist methods_exist = methods_to_check.any? do |method_name| member.method_defined?(method_name) || member.private_method_defined?(method_name) end field_type.install(member) unless methods_exist end end # Copy features configuration if parent_class.respond_to?(:features_enabled) && parent_class.features_enabled&.any? member.instance_variable_set(:@features_enabled, parent_class.features_enabled.dup) end # Copy other configuration using consistent instance variable access if (prefix = parent_class.instance_variable_get(:@prefix)) member.instance_variable_set(:@prefix, prefix) end if (suffix = parent_class.instance_variable_get(:@suffix)) member.instance_variable_set(:@suffix, suffix) end if (logical_db = parent_class.instance_variable_get(:@logical_database)) member.instance_variable_set(:@logical_database, logical_db) end if (default_exp = parent_class.instance_variable_get(:@default_expiration)) member.instance_variable_set(:@default_expiration, default_exp) end # Copy DataType relationships if parent_class.&.any? member.instance_variable_set(:@class_related_fields, parent_class..dup) end if parent_class.&.any? member.instance_variable_set(:@related_fields, parent_class..dup) end if parent_class.instance_variable_get(:@has_related_fields) member.instance_variable_set(:@has_related_fields, parent_class.instance_variable_get(:@has_related_fields)) end end # Track all classes that inherit from Horreum Familia.members << member # Set up automatic instance tracking using built-in class_sorted_set member.class_sorted_set :instances super end |
Instance Method Details
#generate_id ⇒ Object
335 336 337 |
# File 'lib/familia/horreum.rb', line 335 def generate_id @objid ||= Familia.generate_id end |
#identifier ⇒ Object
Determines the unique identifier for the instance This method is used to generate dbkeys for the object Returns nil for unsaved objects (following standard ORM patterns)
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 |
# File 'lib/familia/horreum.rb', line 304 def identifier definition = self.class.identifier_field return nil if definition.nil? # Call the identifier field or proc (validation already done at class definition time) unique_id = case definition when Symbol, String send(definition) when Proc definition.call(self) end # Return nil for unpopulated identifiers (like unsaved ActiveRecord objects) # Only raise errors when the identifier is actually needed for db operations return nil if unique_id.nil? || unique_id.to_s.empty? unique_id end |
#init(*args, **kwargs) ⇒ Object
226 227 228 |
# File 'lib/familia/horreum.rb', line 226 def init(*args, **kwargs) # Default no-op end |
#initialize_relatives ⇒ Object
Sets up related Database objects for the instance This method is crucial for establishing Valkey/Redis-based relationships
This needs to be called in the initialize method.
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 |
# File 'lib/familia/horreum.rb', line 235 def initialize_relatives # Generate instances of each DataType. These need to be # unique for each instance of this class so they can piggyback # on the specifc index of this instance. # # i.e. # familia_object.dbkey == v1:bone:INDEXVALUE:object # familia_object.related_object.dbkey == v1:bone:INDEXVALUE:name # self.class..each_pair do |name, data_type_definition| klass = data_type_definition.klass opts = data_type_definition.opts Familia.trace :INITIALIZE_RELATIVES, nil, "#{name} => #{klass} #{opts.keys}" if Familia.debug? # As a subclass of Familia::Horreum, we add ourselves as the parent # automatically. This is what determines the dbkey for DataType # instance and which database connection. # # e.g. If the parent's dbkey is `customer:customer_id:object` # then the dbkey for this DataType instance will be # `customer:customer_id:name`. # # Store reference to the instance for lazy ParentDefinition creation opts[:parent] = self suffix_override = opts.fetch(:suffix, name) # Instantiate the DataType object and below we store it in # an instance variable. = klass.new suffix_override, opts # Freezes the related_object, making it immutable. # This ensures the object's state remains consistent and prevents any modifications, # safeguarding its integrity and making it thread-safe. # Any attempts to change the object after this will raise a FrozenError. .freeze # e.g. customer.name #=> `#<Familia::HashKey:0x0000...>` instance_variable_set :"@#{name}", end end |
#initialize_with_keyword_args_deserialize_value(**fields) ⇒ Object
277 278 279 280 281 |
# File 'lib/familia/horreum.rb', line 277 def initialize_with_keyword_args_deserialize_value(**fields) # Deserialize Database string values back to their original types deserialized_fields = fields.transform_values { |value| deserialize_value(value) } initialize_with_keyword_args(**deserialized_fields) end |
#optimistic_refresh(**fields) ⇒ Array
A thin wrapper around the private initialize method that accepts a field hash and refreshes the existing object.
This method is part of horreum.rb rather than serialization.rb because it operates solely on the provided values and doesn't query Database or other external sources. That's why it's called "optimistic" refresh: it assumes the provided values are correct and updates the object accordingly.
296 297 298 299 |
# File 'lib/familia/horreum.rb', line 296 def optimistic_refresh(**fields) Familia.ld "[optimistic_refresh] #{self.class} #{dbkey} #{fields.keys}" initialize_with_keyword_args_deserialize_value(**fields) end |
#to_s ⇒ Object
The principle is: If Familia objects have to_s, then they should work
everywhere strings are expected, including as Database hash field names.
341 342 343 344 345 346 347 348 |
# File 'lib/familia/horreum.rb', line 341 def to_s # Enable polymorphic string usage for Familia objects # This allows passing Familia objects directly where strings are expected # without requiring explicit .identifier calls return super if identifier.to_s.empty? identifier.to_s end |