Class: Familia::Horreum
- Inherits:
-
Object
- Object
- Familia::Horreum
- Includes:
- Base, Connection, DatabaseCommands, Serialization, Settings, Utils
- Defined in:
- lib/familia/horreum.rb,
lib/familia/horreum/utils.rb,
lib/familia/horreum/settings.rb,
lib/familia/horreum/connection.rb,
lib/familia/horreum/serialization.rb,
lib/familia/horreum/database_commands.rb,
lib/familia/horreum/definition_methods.rb,
lib/familia/horreum/management_methods.rb,
lib/familia/horreum/related_fields_management.rb
Overview
Familia::Horreum
Defined Under Namespace
Modules: Connection, DatabaseCommands, DefinitionMethods, ManagementMethods, RelatedFieldsManagement, Serialization, Settings, Utils
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_relations ⇒ Object
readonly
Returns the value of attribute has_relations.
-
.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 ⇒ Redis
Summon the mystical Database connection from the depths of instance or class.
Attributes included from Connection
Attributes included from Settings
#dump_method, #load_method, #suffix
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 Redis-related data.
-
#initialize_relatives ⇒ Object
Sets up related Database objects for the instance This method is crucial for establishing 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 DatabaseCommands
#current_expiration, #data_type, #decr, #decrby, #delete!, #exists?, #expire, #field_count, #hget, #hgetall, #hkeys, #hmset, #hset, #hstrlen, #hvals, #incr, #incrby, #incrbyfloat, #key?, #move, #remove_field
Methods included from Serialization
#apply_fields, #batch_update, #clear_fields!, #commit_fields, #deserialize_value, #destroy!, #refresh, #refresh!, #save, #serialize_value, #to_a, #to_h
Methods included from Connection
#connect, #pipeline, #transaction
Methods included from Settings
#logical_database, #logical_database=, #opts, #prefix
Methods included from Utils
Methods included from Base
add_feature, #update_expiration, #uuid
Constructor Details
#initialize(*args, **kwargs) ⇒ Horreum
Instance initialization This method sets up the object’s state, including Redis-related data.
Usage:
Session.new(“abc123”, “user456”) # positional (brittle) Session.new(sessid: “abc123”, custid: “user456”) # hash (robust) Session.new(“abc123”, custid: “user456”) # legacy hash (robust)
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 |
# File 'lib/familia/horreum.rb', line 86 def initialize(*args, **kwargs) Familia.ld "[Horreum] Initializing #{self.class}" 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 three strategies: # # 1. **Keyword Arguments** (Recommended): Order-independent field assignment # Example: Customer.new(name: "John", email: "john@example.com") # - Robust against field reordering # - Self-documenting # - Only sets provided fields # # 2. **Positional Arguments** (Legacy): Field assignment by definition order # Example: Customer.new("john@example.com", "password123") # - Brittle: breaks if field order changes # - Compact syntax # - Maps to fields in class definition order # # 3. **No Arguments**: Object created with all fields as nil # - Minimal memory footprint in Redis # - Fields set on-demand via accessors or save() # - Avoids default value conflicts with nil-skipping serialization # # Note: We iterate over self.class.fields (not kwargs) to ensure only # defined fields are set, preventing typos from creating undefined attributes. # if kwargs.any? initialize_with_keyword_args(**kwargs) elsif args.any? initialize_with_positional_args(*args) else Familia.ld "[Horreum] #{self.class} initialized with no arguments" # Default values are intentionally NOT set here to: # - Maintain Database memory efficiency (only store non-nil values) # - Avoid conflicts with nil-skipping serialization logic # - Preserve consistent exists? behavior (empty vs default-filled objects) # - Keep initialization lightweight for unused fields 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?
59 60 61 |
# File 'lib/familia/horreum.rb', line 59 def dbclient=(value) @dbclient = value end |
.dump_method=(value) ⇒ Object (writeonly)
TODO: Where are we calling dbclient= from now with connection pool?
59 60 61 |
# File 'lib/familia/horreum.rb', line 59 def dump_method=(value) @dump_method = value end |
.has_relations ⇒ Object (readonly)
Returns the value of attribute has_relations.
60 61 62 |
# File 'lib/familia/horreum.rb', line 60 def has_relations @has_relations end |
.load_method=(value) ⇒ Object (writeonly)
TODO: Where are we calling dbclient= from now with connection pool?
59 60 61 |
# File 'lib/familia/horreum.rb', line 59 def load_method=(value) @load_method = value end |
.parent ⇒ Object
Returns the value of attribute parent.
57 58 59 |
# File 'lib/familia/horreum.rb', line 57 def parent @parent end |
.valid_command_return_values ⇒ Object (readonly)
Returns the value of attribute valid_command_return_values.
30 31 32 |
# File 'lib/familia/horreum/serialization.rb', line 30 def valid_command_return_values @valid_command_return_values end |
Instance Attribute Details
#dbclient ⇒ Redis
Summon the mystical Database connection from the depths of instance or class.
This method is like a magical divining rod, always pointing to the nearest source of Database goodness. It first checks if we have a personal Redis connection (@dbclient), and if not, it borrows the class’s connection.
292 293 294 295 |
# File 'lib/familia/horreum.rb', line 292 def dbclient Fiber[:familia_transaction] || @dbclient || self.class.dbclient # conn.select(self.class.logical_database) end |
Class Method Details
.inherited(member) ⇒ Object
Extends ClassMethods to subclasses and tracks Familia members
63 64 65 66 67 68 69 70 71 72 73 74 |
# File 'lib/familia/horreum.rb', line 63 def inherited(member) Familia.trace :HORREUM, nil, "Welcome #{member} to the family", caller(1..1) if Familia.debug? member.extend(DefinitionMethods) member.extend(ManagementMethods) member.extend(Connection) member.extend(Features) # Tracks all the classes/modules that include Familia. It's # 10pm, do you know where you Familia members are? Familia.members << member super end |
Instance Method Details
#generate_id ⇒ Object
297 298 299 |
# File 'lib/familia/horreum.rb', line 297 def generate_id @objid ||= Familia.generate_id # rubocop:disable Naming/MemoizedInstanceVariableName 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)
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 |
# File 'lib/familia/horreum.rb', line 259 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 Redis operations return nil if unique_id.nil? || unique_id.to_s.empty? unique_id end |
#init(*args, **kwargs) ⇒ Object
140 141 142 |
# File 'lib/familia/horreum.rb', line 140 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 Redis-based relationships
This needs to be called in the initialize method.
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 |
# File 'lib/familia/horreum.rb', line 149 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.ld "[#{self.class}] initialize_relatives #{name} => #{klass} #{opts.keys}" # 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`. # opts[:parent] = self # unless opts.key(:parent) 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
232 233 234 235 236 |
# File 'lib/familia/horreum.rb', line 232 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.
251 252 253 254 |
# File 'lib/familia/horreum.rb', line 251 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.
303 304 305 306 307 308 309 310 |
# File 'lib/familia/horreum.rb', line 303 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 |