Module: ActiveRecordCompose::DelegateAttribute

Extended by:
ActiveSupport::Concern
Included in:
Model
Defined in:
lib/active_record_compose/delegate_attribute.rb

Overview

Delegate Attribute

It provides a macro description that expresses access to the attributes of the AR model through delegation.

class AccountRegistration < ActiveRecordCompose::Model
  def initialize(, attributes = {})
    @account = 
    super(attributes)
    models.push()
  end

  attribute :original_attribute, :string, default: 'qux'

  # like a `delegate :name, :name=, to: :account`
  delegate_attribute :name, to: :account

  private

  attr_reader :account
end

 = Account.new
.name = 'foo'

registration = AccountRegistration.new()
registration.name  #=> 'foo'  # delegate to account#name

registration.name = 'bar'  # delegate to account#name=
.name  #=> 'bar'

# Attributes defined in delegate_attribute will be included in the original `#attributes`.
registration.attributes  #=> { 'original_attribute' => 'qux', 'name' => 'bar' }

Defined Under Namespace

Modules: ClassMethods

Instance Method Summary collapse

Instance Method Details

#attributesHash

Returns a hash with the attribute name as key and the attribute value as value. Attributes declared with ‘delegate_attribute` are also merged.

Returns:

  • (Hash)

    hash with the attribute name as key and the attribute value as value.



65
66
67
68
69
70
71
72
# File 'lib/active_record_compose/delegate_attribute.rb', line 65

def attributes
  attrs = defined?(super) ? super : {} # steep:ignore
  delegates = delegated_attributes # steep:ignore

  # @type var attrs: Hash[String, untyped]
  # @type var delegates: Array[String]
  attrs.merge(delegates.to_h { [_1, public_send(_1)] })
end