Module: Literal::Attributes

Extended by:
Types
Defined in:
lib/literal/attributes.rb

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

Class Method Details

.extended(base) ⇒ Object



30
31
32
# File 'lib/literal/attributes.rb', line 30

def self.extended(base)
  base.include(Literal::Initializer)
end

Instance Method Details

#__attributes__Object



25
26
27
28
# File 'lib/literal/attributes.rb', line 25

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

#attribute(name, type, reader: false, writer: :private) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/literal/attributes.rb', line 4

def attribute(name, type, reader: false, writer: :private)
  __attributes__ << name

  writer_name = :"#{name}="
  ivar_name = :"@#{name}"

  define_method writer_name do |value|
    raise Literal::TypeError, "Expected `#{value.inspect}` to be a `#{type.inspect}`." unless type === value
    instance_variable_set(ivar_name, value)
  end

  private writer_name unless writer == :public

  if reader
    attr_reader name
    private name unless reader == :public
  end

  name
end