Class: Upgrow::ImmutableObject

Inherits:
Object
  • Object
show all
Defined in:
lib/upgrow/immutable_object.rb

Overview

A read-only Object. An Immutable Object is initialized with its attributes and subsequent state changes are not permitted.

Direct Known Subclasses

BasicModel, Error, Input

Class Attribute Summary collapse

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(**attributes) ⇒ ImmutableObject

Initializes a new Immutable Object with the given member values.

Parameters:

  • attributes (Hash<Symbol, Object>)

    the list of values for each attribute of the Immutable Object.

Raises:

  • (ArgumentError)

    if the given argument is not an attribute.



37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/upgrow/immutable_object.rb', line 37

def initialize(**attributes)
  absent_attributes = attributes.keys - self.class.schema.attribute_names

  if absent_attributes.any?
    raise ArgumentError, "Unknown attribute #{absent_attributes}"
  end

  @attributes = self.class.schema.attribute_names.to_h do |name|
    [name, attributes[name]]
  end.freeze

  freeze
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args, &block) ⇒ Object (private)



53
54
55
56
# File 'lib/upgrow/immutable_object.rb', line 53

def method_missing(name, *args, &block)
  super unless attributes.include?(name)
  attributes.fetch(name)
end

Class Attribute Details

.schemaObject

Returns the value of attribute schema.



12
13
14
# File 'lib/upgrow/immutable_object.rb', line 12

def schema
  @schema
end

Instance Attribute Details

#attributesObject (readonly)

Returns the value of attribute attributes.



29
30
31
# File 'lib/upgrow/immutable_object.rb', line 29

def attributes
  @attributes
end

Class Method Details

.attribute(name) ⇒ Object

Defines an attribute in the Immutable Object Schema.

Parameters:

  • name (Symbol)

    the name of the attribute.



17
18
19
# File 'lib/upgrow/immutable_object.rb', line 17

def attribute(name)
  schema.attribute(name)
end