Class: Mimi::Core::Struct

Inherits:
Object
  • Object
show all
Defined in:
lib/mimi/core/struct.rb

Overview

Mimi::Core::Struct is a simple immutable data structure.

It allows instantiating an object from a set of attributes and makes them available as object methods and Hash paramaters: my_object = Mimi::Core::Struct.new(a: 1, b: 2)

my_object.a # => 1 my_object[:a] # => 1 my_object['a'] # => 1

It only allows access to defined attributes: my_object.c # => NoMethodError my_object[:c] # => NameError

Instance Method Summary collapse

Constructor Details

#initialize(attrs = {}) ⇒ Struct

Creates a Struct object from a set of attributes

Parameters:

  • attrs (Hash) (defaults to: {})

Raises:

  • (ArgumentError)


26
27
28
29
30
# File 'lib/mimi/core/struct.rb', line 26

def initialize(attrs = {})
  raise ArgumentError, "Hash is expected as attrs" unless attrs.is_a?(Hash)
  attributes = attrs.map { |k, v| [k.to_sym, v.dup] }.to_h
  initialize_attributes(attributes)
end

Instance Method Details

#==(other) ⇒ true, false

Compares two Structs, comparing only their attribute values

Parameters:

Returns:

  • (true, false)


58
59
60
61
62
63
64
# File 'lib/mimi/core/struct.rb', line 58

def ==(other)
  if !other.is_a?(Mimi::Core::Struct) && !other.is_a?(Hash)
    raise TypeError, "Cannot compare Mimi::Core::Struct and #{other.class}"
  end
  other_as_hash = other.is_a?(Hash) ? other : other.to_h
  self.to_h == other_as_hash
end

#[](attr_name) ⇒ Object

Fetches attribute by its name

Parameters:

  • name (String, Symbol)

Returns:

  • (Object)

    attribute's value



37
38
39
40
41
42
43
# File 'lib/mimi/core/struct.rb', line 37

def [](attr_name)
  attr_name = attr_name.to_sym
  unless @attributes.key?(attr_name)
    raise NameError, "undefined attribute #{attr_name.inspect}"
  end
  @attributes[attr_name]
end

#dupMimi::Core::Struct

Returns a new copy of a Mimi::Core::Struct object, deep copying its attributes

Returns:



70
71
72
73
74
# File 'lib/mimi/core/struct.rb', line 70

def dup
  new_object = super
  new_object.send :initialize_attributes, @attributes
  new_object
end

#to_hHash

Returns Struct attributes as a Hash

Returns:



49
50
51
# File 'lib/mimi/core/struct.rb', line 49

def to_h
  @attributes
end