Class: Literal::Struct

Inherits:
Object
  • Object
show all
Extended by:
Types
Includes:
Initializer
Defined in:
lib/literal/struct.rb

Direct Known Subclasses

Data

Constant Summary

Constants included from Types

Types::BooleanType

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Types

_Any, _Array, _Boolean, _Class, _Enumerable, _Float, _Hash, _Integer, _Interface, _Maybe, _Set, _Tuple, _Union

Constructor Details

#initializeStruct

Returns a new instance of Struct.



5
6
7
8
# File 'lib/literal/struct.rb', line 5

def initialize(...)
  @attributes = {}
  super
end

Class Method Details

.__attributes__Object



10
11
12
13
# File 'lib/literal/struct.rb', line 10

def self.__attributes__
  return @__attributes__ if defined?(@__attributes__)
  @__attributes__ = superclass.is_a?(self) ? superclass.__attributes__.dup : []
end

.attribute(name, type, writer: :private) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/literal/struct.rb', line 15

def self.attribute(name, type, writer: :private)
  __attributes__ << name

  writer_name = :"#{name}="

  define_method writer_name do |value|
    raise Literal::TypeError, "Expected #{name}: `#{value.inspect}` to be: `#{type.inspect}`." unless type === value
    @attributes[name] = value
  end

  define_method name do
    @attributes[name]
  end

  name
end

Instance Method Details

#to_hObject



32
33
34
# File 'lib/literal/struct.rb', line 32

def to_h
  @attributes.dup
end