Module: Familia::Horreum::ClassMethods

Includes:
RelationsManagement, 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 Redis operations and object management.

Key features:

  • Includes RelationsManagement for Redis-type field handling

  • Defines methods for managing fields, identifiers, and Redis keys

  • Provides utility methods for working with Redis objects

Instance Attribute Summary collapse

Attributes included from Settings

#delim, #ttl

Instance Method Summary collapse

Methods included from RelationsManagement

#attach_class_redis_object_relation, #attach_instance_redis_object_relation, included

Methods included from Settings

#default_suffix

Instance Attribute Details

#dump_methodObject



405
406
407
# File 'lib/familia/horreum/class_methods.rb', line 405

def dump_method
  @dump_method || :to_json # Familia.dump_method
end

#load_methodObject



409
410
411
# File 'lib/familia/horreum/class_methods.rb', line 409

def load_method
  @load_method || :from_json # Familia.load_method
end

#parentObject

Returns the value of attribute parent.



36
37
38
# File 'lib/familia/horreum/class_methods.rb', line 36

def parent
  @parent
end

#redisRedis

Returns the Redis connection for the class.

This method retrieves the Redis connection instance for the class. If no connection is set, it initializes a new connection using the provided URI or database configuration.

Returns:

  • (Redis)

    the Redis connection instance.



47
48
49
# File 'lib/familia/horreum/class_methods.rb', line 47

def redis
  @redis || Familia.redis(uri || db)
end

Instance Method Details

#all(suffix = nil) ⇒ Object



161
162
163
164
165
# File 'lib/familia/horreum/class_methods.rb', line 161

def all(suffix = nil)
  suffix ||= self.suffix
  # objects that could not be parsed will be nil
  keys(suffix).filter_map { |k| from_rediskey(k) }
end

#any?(filter = '*') ⇒ Boolean

Returns:

  • (Boolean)


167
168
169
# File 'lib/familia/horreum/class_methods.rb', line 167

def any?(filter = '*')
  size(filter) > 0
end

#class_redis_typesObject



133
134
135
136
# File 'lib/familia/horreum/class_methods.rb', line 133

def class_redis_types
  @class_redis_types ||= {}
  @class_redis_types
end

#class_redis_types?(name) ⇒ Boolean

Returns:

  • (Boolean)


138
139
140
# File 'lib/familia/horreum/class_methods.rb', line 138

def class_redis_types?(name)
  class_redis_types.key? name.to_s.to_sym
end

#create(*args, **kwargs) ⇒ Object

Note:

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.

Examples:

Creating an object with keyword arguments

User.create(name: "John", age: 30)

Creating an object with positional and keyword arguments (not recommended)

Product.create("SKU123", name: "Widget", price: 9.99)

Parameters:

  • *args (Array)

    Variable number of positional arguments to be passed to the constructor.

  • **kwargs (Hash)

    Keyword arguments to be passed to the constructor.

Returns:

  • (Object)

    The newly created and persisted instance.

Raises:

  • (Familia::Problem)

    If an instance with the same identifier already exists.

See Also:



221
222
223
224
225
226
227
# File 'lib/familia/horreum/class_methods.rb', line 221

def create *args, **kwargs
  fobj = new(*args, **kwargs)
  raise Familia::Problem, "#{self} already exists: #{fobj.rediskey}" if fobj.exists?

  fobj.save
  fobj
end

#db(v = nil) ⇒ Object



151
152
153
154
# File 'lib/familia/horreum/class_methods.rb', line 151

def db(v = nil)
  @db = v unless v.nil?
  @db || parent&.db
end

#destroy!(identifier, suffix = nil) ⇒ Boolean

Destroys an object in Redis with the given identifier.

This method constructs the full Redis key using the provided identifier and suffix, then removes the corresponding key from Redis.

Examples:

User.destroy!(123)  # Removes user:123:object from Redis

Parameters:

  • identifier (String, Integer)

    The unique identifier for the object to destroy.

  • suffix (Symbol, nil) (defaults to: nil)

    The suffix to use in the Redis key (default: class suffix).

Returns:

  • (Boolean)

    true if the object was successfully destroyed, false otherwise.



360
361
362
363
364
365
366
367
368
369
# File 'lib/familia/horreum/class_methods.rb', line 360

def destroy!(identifier, suffix = nil)
  suffix ||= self.suffix
  return false if identifier.to_s.empty?

  objkey = rediskey identifier, suffix

  ret = redis.del objkey
  Familia.trace :DELETED, redis, "#{objkey}: #{ret.inspect}", caller(1..1) if Familia.debug?
  ret.positive?
end

#exists?(identifier, suffix = nil) ⇒ Boolean

Checks if an object with the given identifier exists in Redis.

This method constructs the full Redis key using the provided identifier and suffix, then checks if the key exists in Redis.

Examples:

User.exists?(123)  # Returns true if user:123:object exists in Redis

Parameters:

  • identifier (String, Integer)

    The unique identifier for the object.

  • suffix (Symbol, nil) (defaults to: nil)

    The suffix to use in the Redis key (default: class suffix).

Returns:

  • (Boolean)

    true if the object exists, false otherwise.



336
337
338
339
340
341
342
343
344
345
346
# File 'lib/familia/horreum/class_methods.rb', line 336

def exists?(identifier, suffix = nil)
  suffix ||= self.suffix
  return false if identifier.to_s.empty?

  objkey = rediskey identifier, suffix

  ret = redis.exists objkey
  Familia.trace :EXISTS, redis, "#{objkey} #{ret.inspect}", caller(1..1) if Familia.debug?

  ret.positive? # differs from redis API but I think it's okay bc `exists?` is a predicate method.
end

#fast_writer!(name) ⇒ Object

Defines a fast writer method with a bang (!) suffix for a given attribute name. Fast writer methods are used to immediately persist attribute values to Redis. Calling a fast writer method has no effect on any of the object’s other attributes and does not trigger a called to update the object’s expiration time.

The dynamically defined method performs the following:

  • Checks if the correct number of arguments is provided (exactly one).

  • Converts the provided value to a format suitable for Redis storage.

  • Uses the existing accessor method to set the attribute value.

  • Persists the value to Redis immediately using the hset command.

  • 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.

Parameters:

  • name (Symbol, String)

    the name of the attribute for which the writer method is defined.

Raises:

  • (ArgumentError)

    if the wrong number of arguments is provided.

  • (RuntimeError)

    if an exception occurs during the execution of the method.



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
# File 'lib/familia/horreum/class_methods.rb', line 99

def fast_writer!(name)
  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 1)" if args.size != 1

    val = args.first

    begin
      # Trace the operation if debugging is enabled.
      Familia.trace :FAST_WRITER, redis, "#{name}: #{val.inspect}", caller(1..1) if Familia.debug?

      # Convert the provided value to a format suitable for Redis storage.
      prepared = to_redis(val)
      Familia.ld "[.fast_writer!] #{name} val: #{val.class} prepared: #{prepared.class}"

      # Use the existing accessor method to set the attribute value.
      send :"#{name}=", val

      # Persist the value to Redis 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.message}", 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.

Parameters:

  • name (Symbol, String)

    the name of the field to define.



73
74
75
76
77
78
79
# File 'lib/familia/horreum/class_methods.rb', line 73

def field(name)
  fields << name
  attr_accessor name

  # Every field gets a fast writer method for immediately persisting
  fast_writer! name
end

#fieldsObject

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]`.



128
129
130
131
# File 'lib/familia/horreum/class_methods.rb', line 128

def fields
  @fields ||= []
  @fields
end

#find(suffix = '*') ⇒ Array<String>

Finds all keys in Redis matching the given suffix pattern.

This method searches for all Redis keys that match the given suffix pattern. It uses the class’s rediskey method to construct the search pattern.

Examples:

User.find  # Returns all keys matching user:*:object
User.find('active')  # Returns all keys matching user:*:active

Parameters:

  • suffix (String) (defaults to: '*')

    The suffix pattern to match (default: ‘*’).

Returns:

  • (Array<String>)

    An array of matching Redis keys.



383
384
385
# File 'lib/familia/horreum/class_methods.rb', line 383

def find(suffix = '*')
  redis.keys(rediskey('*', suffix)) || []
end

#from_identifier(identifier, suffix = nil) ⇒ Object? Also known as: load

Retrieves and instantiates an object from Redis using its identifier.

This method constructs the full Redis key using the provided identifier and suffix, then delegates to ‘from_rediskey` 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.

Examples:

User.from_identifier(123)  # Equivalent to User.from_rediskey("user:123:object")

Parameters:

  • identifier (String, Integer)

    The unique identifier for the object.

  • suffix (Symbol) (defaults to: nil)

    The suffix to use in the Redis key (default: :object).

Returns:

  • (Object, nil)

    An instance of the class if found, nil otherwise.



312
313
314
315
316
317
318
319
320
321
# File 'lib/familia/horreum/class_methods.rb', line 312

def from_identifier(identifier, suffix = nil)
  suffix ||= self.suffix
  return nil if identifier.to_s.empty?

  objkey = rediskey(identifier, suffix)

  Familia.ld "[.from_identifier] #{self} from key #{objkey})"
  Familia.trace :FROM_IDENTIFIER, Familia.redis(uri), objkey, caller(1..1).first if Familia.debug?
  from_rediskey objkey
end

#from_rediskey(objkey) ⇒ Object?

Retrieves and instantiates an object from Redis using the full object key.

This method performs a two-step process to safely retrieve and instantiate objects:

  1. 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 ‘hgetall` returning an empty hash for non-existent keys, which could lead to the creation of “empty” objects.

  2. 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.

Examples:

User.from_rediskey("user:123")  # Returns a User instance if it exists,
nil otherwise

Parameters:

  • objkey (String)

    The full Redis key for the object.

Returns:

  • (Object, nil)

    An instance of the class if the key exists, nil otherwise.

Raises:

  • (ArgumentError)

    If the provided key is empty.



270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
# File 'lib/familia/horreum/class_methods.rb', line 270

def from_rediskey(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 = redis.exists(objkey).positive?

  Familia.ld "[.from_rediskey] #{self} from key #{objkey} (exists: #{does_exist})"
  Familia.trace :FROM_KEY, redis, 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 = redis.hgetall(objkey) # horreum objects are persisted as redis hashes
  Familia.trace :FROM_KEY2, redis, "#{objkey}: #{obj.inspect}", caller(1..1) if Familia.debug?

  new(**obj)
end

#identifier(val = nil) ⇒ Object

Sets or retrieves the unique identifier for the class.

This method defines or returns the unique identifier used to generate the Redis key for the object. If a value is provided, it sets the identifier; otherwise, it returns the current identifier.

Parameters:

  • val (Object) (defaults to: nil)

    the value to set as the identifier (optional).

Returns:

  • (Object)

    the current identifier.



60
61
62
63
# File 'lib/familia/horreum/class_methods.rb', line 60

def identifier(val = nil)
  @identifier = val if val
  @identifier
end

#multiget(*ids) ⇒ Object



229
230
231
232
# File 'lib/familia/horreum/class_methods.rb', line 229

def multiget(*ids)
  ids = rawmultiget(*ids)
  ids.filter_map { |json| from_json(json) }
end

#prefix(a = nil) ⇒ Object



180
181
182
183
# File 'lib/familia/horreum/class_methods.rb', line 180

def prefix(a = nil)
  @prefix = a if a
  @prefix || name.downcase.gsub('::', Familia.delim).to_sym
end

#rawmultiget(*ids) ⇒ Object



234
235
236
237
238
239
240
# File 'lib/familia/horreum/class_methods.rb', line 234

def rawmultiget(*ids)
  ids.collect! { |objid| rediskey(objid) }
  return [] if ids.compact.empty?

  Familia.trace :MULTIGET, redis, "#{ids.size}: #{ids}", caller(1..1) if Familia.debug?
  redis.mget(*ids)
end

#redis_object?(name) ⇒ Boolean

Returns:

  • (Boolean)


142
143
144
# File 'lib/familia/horreum/class_methods.rb', line 142

def redis_object?(name)
  redis_types.key? name.to_s.to_sym
end

#redis_typesObject



146
147
148
149
# File 'lib/familia/horreum/class_methods.rb', line 146

def redis_types
  @redis_types ||= {}
  @redis_types
end

#rediskey(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 RedisType objects at the class level are created without the global default ‘object’ suffix. See RedisType#rediskey “parent_class?” for more details.

Raises:



397
398
399
400
401
402
403
# File 'lib/familia/horreum/class_methods.rb', line 397

def rediskey(identifier, suffix = self.suffix)
  # Familia.ld "[.rediskey] #{identifier} for #{self} (suffix:#{suffix})"
  raise NoIdentifier, self if identifier.to_s.empty?

  identifier &&= identifier.to_s
  Familia.rediskey(prefix, identifier, suffix)
end

#size(filter = '*') ⇒ Object



171
172
173
# File 'lib/familia/horreum/class_methods.rb', line 171

def size(filter = '*')
  redis.keys(rediskey(filter)).compact.size
end

#suffix(a = nil, &blk) ⇒ Object



175
176
177
178
# File 'lib/familia/horreum/class_methods.rb', line 175

def suffix(a = nil, &blk)
  @suffix = a || blk if a || !blk.nil?
  @suffix || Familia.default_suffix
end

#uri(v = nil) ⇒ Object



156
157
158
159
# File 'lib/familia/horreum/class_methods.rb', line 156

def uri(v = nil)
  @uri = v unless v.nil?
  @uri || parent&.uri
end