Module: Cattri::InitializerPatch

Defined in:
lib/cattri/initializer_patch.rb

Overview

Provides a patch to ‘#initialize` that ensures all final attributes are initialized with their default values if not already set.

This module is prepended into Cattri-including classes to enforce write-once semantics for instance-level ‘final: true` attributes.

Examples:

class MyClass
  include Cattri

  cattri :id, -> { SecureRandom.uuid }, final: true
end

MyClass.new # => will have a UUID assigned to @id unless explicitly set

Instance Method Summary collapse

Instance Method Details

#initialize(*args, **kwargs) { ... } ⇒ void

Hooked constructor that initializes final attributes using their defaults if no value has been set by the user.

Parameters:

  • args (Array)

    any positional arguments passed to initialize

  • kwargs (Hash)

    any keyword arguments passed to initialize

Yields:

  • an optional block to pass to ‘super`



26
27
28
29
30
31
32
33
34
35
36
# File 'lib/cattri/initializer_patch.rb', line 26

def initialize(*args, **kwargs, &block)
  super

  registry = self.class.send(:attribute_registry)
  registry.defined_attributes(with_ancestors: true).each_value do |attribute| # steep:ignore
    next if cattri_variable_defined?(attribute.ivar) # steep:ignore
    next unless attribute.final?

    cattri_variable_set(attribute.ivar, attribute.evaluate_default, final: true) # steep:ignore
  end
end