Class: Familia::JsonStringKey

Inherits:
DataType
  • Object
show all
Includes:
DataType::ScalarBase
Defined in:
lib/familia/data_type/types/json_stringkey.rb

Overview

Note:

This class intentionally does NOT include increment/decrement or other raw string operations that are incompatible with JSON serialization.

Note:

Performance: Each call to value, to_s, to_i, to_f makes a Redis roundtrip. If you need the value multiple times and don't expect it to change, store it in a local variable:

Inefficient (3 Redis calls):

puts json_str.to_s puts json_str.to_i puts json_str.to_f

Efficient (1 Redis call):

val = json_str.value puts val.to_s puts val.to_i puts val.to_f

JsonStringKey - A string DataType that uses JSON serialization for type preservation.

Unlike StringKey which uses raw string serialization (to support Redis operations like INCR/DECR/APPEND), JsonStringKey uses the base DataType's JSON serialization to preserve Ruby types across the Redis storage boundary.

Examples:

Basic usage

class MyIndex < Familia::Horreum
  class_json_string :last_synced_at, default: 0.0
end

MyIndex.last_synced_at = Familia.now.to_f  # Stored as JSON number
MyIndex.last_synced_at  #=> 1704067200.123 (Float preserved)

Type preservation

json_str.value = 42        # Stored in Redis as: 42 (JSON number)
json_str.value = true      # Stored in Redis as: true (JSON boolean)
json_str.value = [1, 2, 3] # Stored in Redis as: [1,2,3] (JSON array)

Instance Attribute Summary collapse

Attributes included from Settings

#current_key_version, #default_expiration, #delim, #encryption_hkdf_salt, #encryption_hkdf_salt_history, #encryption_keys, #encryption_personalization, #encryption_personalization_history, #logical_database, #prefix, #raise_on_unsaved_parent_write, #schema_path, #schema_validator, #schemas, #strict_write_order, #suffix, #transaction_mode

Instance Method Summary collapse

Methods included from DataType::ScalarBase

#scalar_type?

Methods included from Features::Autoloader

autoload_files, included, normalize_to_config_name

Methods included from DataType::Serialization

#deserialize_value, #deserialize_values, #deserialize_values_with_nil, #serialize_value, #strip_legacy_json_encoding

Methods included from DataType::DatabaseCommands

#current_expiration, #delete!, #echo, #exists?, #expire, #expireat, #move, #persist, #rename, #renamenx, #type

Methods included from DataType::Connection

#dbclient, #dbkey, #uri

Methods included from Connection::Behavior

#connect, #create_dbclient, #multi, #normalize_uri, #pipeline, #pipelined, #transaction, #uri=, #url, #url=, #with_connection_scope

Methods included from Settings

#configure, #default_suffix, #dirty_write_warnings, #dirty_write_warnings=, #pipelined_mode, #pipelined_mode=

Methods included from Base

add_feature, #as_json, #expired?, #expires?, find_feature, #generate_id, #to_json, #ttl, #update_expiration, #uuid

Constructor Details

This class inherits a constructor from Familia::DataType

Instance Attribute Details

#features_enabled ⇒ Object (readonly) Originally defined in module Features

Returns the value of attribute features_enabled.

#logical_database(val = nil) ⇒ Object Originally defined in module DataType::ClassMethods

#parent ⇒ Object Originally defined in module DataType::ClassMethods

Returns the value of attribute parent.

#prefix ⇒ Object Originally defined in module DataType::ClassMethods

Returns the value of attribute prefix.

#suffix ⇒ Object Originally defined in module DataType::ClassMethods

Returns the value of attribute suffix.

#uri(val = nil) ⇒ Object Originally defined in module DataType::ClassMethods

Returns the value of attribute uri.

Instance Method Details

#char_count ⇒ Integer, Redis::Future Also known as: size, length

Returns the number of characters in the string representation of the value.

Returns:

  • (Integer, Redis::Future) —

    number of characters. Inside a transaction or pipeline, the GET Future (resolves to the raw JSON).



54
55
56
# File 'lib/familia/data_type/types/json_stringkey.rb', line 54

def char_count
  Familia.transform_reply(read_converted(&:to_s)) { |str| str&.size || 0 }
end

#del ⇒ Boolean

Deletes the key from the database.

Returns:

  • (Boolean) —

    true if the key was deleted, false if it didn't exist



132
133
134
135
# File 'lib/familia/data_type/types/json_stringkey.rb', line 132

def del
  ret = dbclient.del dbkey
  Familia.positive?(ret)
end

#empty? ⇒ Boolean, Redis::Future

Checks if the value is nil (key does not exist or has no value).

Reads with a plain GET, like #char_count, and leaves the key and its TTL untouched. A declared default stands in for a missing key, as it does for #value, but unlike #value this never writes the default.

Returns:

  • (Boolean, Redis::Future) —

    true if the value is nil. Inside a transaction or pipeline, the GET Future (resolves to the raw JSON, or nil for a missing key whether or not a default is declared).



147
148
149
# File 'lib/familia/data_type/types/json_stringkey.rb', line 147

def empty?
  Familia.transform_reply(read_converted(&:itself), &:nil?)
end

#init ⇒ Object

Initialization hook (required by DataType contract)



47
# File 'lib/familia/data_type/types/json_stringkey.rb', line 47

def init; end

#setnx(val) ⇒ Boolean, Redis::Future

Sets the value only if the key does not already exist, and refreshes the TTL only when it was set. Inside a transaction or pipeline the SETNX and the refresh are queued as one EVAL that makes the same decision when it runs.

Parameters:

  • val (Object) —

    the value to store

Returns:

  • (Boolean, Redis::Future) —

    true if the key was set, false if it already existed. Inside a transaction or pipeline, the EVAL Future, which resolves to that Boolean (the Future itself is always truthy).



116
117
118
119
120
121
122
123
124
125
126
# File 'lib/familia/data_type/types/json_stringkey.rb', line 116

def setnx(val)
  warn_if_dirty!
  conn = dbclient
  if queued_connection?(conn)
    return queue_conditional_write(conn, :setnx, serialize_value(val)) { |reply| reply == 1 }
  end

  ret = conn.setnx(dbkey, serialize_value(val))
  update_expiration_if_written(ret)
  ret
end

#to_f ⇒ Float?

Returns the float representation of the deserialized value. A conversion method, refused inside a block like #to_s.

Returns:

  • (Float, nil) —

    the deserialized value converted to float, or nil

Raises:



187
188
189
190
191
# File 'lib/familia/data_type/types/json_stringkey.rb', line 187

def to_f
  Familia.assert_replies_available!('JsonStringKey#to_f')

  read_converted(&:to_f)
end

#to_i ⇒ Integer?

Returns the integer representation of the deserialized value. A conversion method, refused inside a block like #to_s.

Returns:

  • (Integer, nil) —

    the deserialized value converted to integer, or nil

Raises:



175
176
177
178
179
# File 'lib/familia/data_type/types/json_stringkey.rb', line 175

def to_i
  Familia.assert_replies_available!('JsonStringKey#to_i')

  read_converted(&:to_i)
end

#to_s ⇒ String?

Returns the string representation of the deserialized value.

Ruby calls to_s implicitly (string interpolation, Array#join, puts) and prints the object's default "#<...>" form when it returns anything but a String, so it cannot hand back a Redis::Future. Use #value to get the GET Future inside a block.

Returns:

  • (String, nil) —

    the deserialized value converted to string, or nil

Raises:



162
163
164
165
166
# File 'lib/familia/data_type/types/json_stringkey.rb', line 162

def to_s
  Familia.assert_replies_available!('JsonStringKey#to_s')

  read_converted(&:to_s)
end

#value ⇒ Object, Redis::Future Also known as: content, get

Returns the current value stored at the key.

If a default option was provided during initialization, the default is set via SETNX (set if not exists) before retrieval, and the TTL is refreshed only when the default was written. Inside a transaction or pipeline the SETNX and the refresh are queued as one EVAL that makes the same decision when it runs, so reading an existing key leaves its TTL unchanged there too. That EVAL adds one Boolean reply to MultiResult#results ahead of the GET reply.

Returns:

  • (Object, Redis::Future) —

    the deserialized value, or the default if not set. Inside a transaction or pipeline, the GET Future (resolves to the raw JSON).



74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/familia/data_type/types/json_stringkey.rb', line 74

def value
  echo :value, Familia.pretty_stack(limit: 1) if Familia.debug
  conn = dbclient
  if @opts.key?(:default)
    default = serialize_value(@opts[:default])
    if queued_connection?(conn)
      queue_conditional_write(conn, :setnx, default) { |reply| reply == 1 }
    else
      update_expiration_if_written(conn.setnx(dbkey, default))
    end
  end
  deserialize_value conn.get(dbkey)
end

#value=(val) ⇒ String Also known as: replace, set

Sets the value at the key.

The value is JSON-serialized before storage, preserving its Ruby type.

Parameters:

  • val (Object) —

    the value to store

Returns:

  • (String) —

    "OK" on success



97
98
99
100
101
102
# File 'lib/familia/data_type/types/json_stringkey.rb', line 97

def value=(val)
  warn_if_dirty!
  ret = dbclient.set(dbkey, serialize_value(val))
  update_expiration
  ret
end