Module: Cattri::InternalStore

Defined in:
lib/cattri/internal_store.rb

Overview

Provides an internal storage mechanism for attribute values defined via cattri.

This module is included into any class or module using Cattri and replaces direct instance variable access with a namespaced store.

It supports enforcement of final semantics and tracks explicit assignments.

Instance Method Summary collapse

Instance Method Details

#cattri_variable_defined?(key) ⇒ Boolean

Checks whether the internal store contains a value for the given key.



31
32
33
# File 'lib/cattri/internal_store.rb', line 31

def cattri_variable_defined?(key)
  __cattri_store.key?(normalize_ivar(key))
end

#cattri_variable_get(key) ⇒ Object?

Fetches the value for a given attribute key from the internal store.



39
40
41
# File 'lib/cattri/internal_store.rb', line 39

def cattri_variable_get(key)
  __cattri_store[normalize_ivar(key)]&.value
end

#cattri_variable_memoize(key, final: false) ⇒ Object

Evaluates and sets a value for the given key only if it hasn't already been set.

If a value is already present, it is returned as-is. Otherwise, the provided block is called to compute the value, which is then stored. If final: true is passed, the value is marked as final and cannot be reassigned.

Yield Returns:

  • (Object)

    the value to memoize if not already present

Raises:



72
73
74
75
76
77
78
# File 'lib/cattri/internal_store.rb', line 72

def cattri_variable_memoize(key, final: false)
  key = normalize_ivar(key)
  return cattri_variable_get(key) if cattri_variable_defined?(key)

  value = yield
  cattri_variable_set(key, value, final: final)
end

#cattri_variable_set(key, value, final: false) ⇒ Object

Sets a value in the internal store for the given attribute key.

Enforces final semantics if a final value was already set.



51
52
53
54
55
56
57
58
59
# File 'lib/cattri/internal_store.rb', line 51

def cattri_variable_set(key, value, final: false)
  key = normalize_ivar(key)
  guard_final!(key)

  __cattri_store[key] = AttributeValue.new(value, final)
  __cattri_set_variables << key

  value
end

#cattri_variablesArray<Symbol>

Returns the list of attribute keys stored by Cattri on this object.

Mimics Ruby's #instance_variables, but only includes attributes defined via cattri and omits the leading @ from names. All keys are returned as frozen symbols (e.g., :enabled instead of :@enabled).



23
24
25
# File 'lib/cattri/internal_store.rb', line 23

def cattri_variables
  __cattri_store.keys.freeze
end