Module: Domainic::Attributer::InstanceMethods

Defined in:
lib/domainic/attributer/instance_methods.rb

Overview

A module providing instance-level attribute functionality

This module defines instance methods for objects that include Domainic::Attributer. It provides initialization handling and attribute serialization capabilities, making it easy to work with attribute values in a consistent way

Examples:

Basic usage

class Person
  include Domainic::Attributer

  argument :name
  option :age, default: nil
  option :role, default: 'user', private_read: true
end

person = Person.new('Alice', age: 30)
person.to_h  # => { name: 'Alice', age: 30 }  # role is private, not included

Author:

Since:

  • 0.1.0

Instance Method Summary collapse

Instance Method Details

#initializeInstanceMethods

Initialize a new instance with attribute values

Handles both positional arguments and keyword options, applying them to their corresponding attributes. This process includes:

  1. Validating required arguments
  2. Applying default values
  3. Type validation and coercion
  4. Change notifications

Examples:

person = Person.new('Alice', age: 30)

Returns:

Raises:

  • (ArgumentError)

    if required arguments are missing

Since:

  • 0.1.0



43
44
45
# File 'lib/domainic/attributer/instance_methods.rb', line 43

def initialize(...)
  DSL::Initializer.new(self).assign!(...)
end

#to_hashHash{Symbol => Object} Also known as: to_h

Convert public attribute values to a hash

Creates a hash containing all public readable attributes and their current values. Any attributes marked as private or protected for reading are excluded from the result

Examples:

person = Person.new('Alice', age: 30)
person.to_h  # => { name: 'Alice', age: 30 }

Returns:

  • (Hash{Symbol => Object})

    hash of attribute names to values

Since:

  • 0.1.0



59
60
61
62
63
64
# File 'lib/domainic/attributer/instance_methods.rb', line 59

def to_hash
  public = self.class.send(:__attributes__).select { |_, attribute| attribute.signature.public_read? }
  public.attributes.each_with_object({}) do |attribute, result|
    result[attribute.name] = public_send(attribute.name)
  end
end