Class: Typical::Type

Inherits:
Object
  • Object
show all
Defined in:
lib/typical/type.rb,
lib/typical/type/list.rb,
lib/typical/type/union.rb,
lib/typical/type/reference.rb

Direct Known Subclasses

List, Reference, Union

Defined Under Namespace

Classes: Array, Hash, List, Reference, Set, Union

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(type) ⇒ Type

Returns a new instance of Type.



30
31
32
# File 'lib/typical/type.rb', line 30

def initialize(type)
  @type = type
end

Instance Attribute Details

#typeObject (readonly)

Returns the value of attribute type.



28
29
30
# File 'lib/typical/type.rb', line 28

def type
  @type
end

Class Method Details

.of(object) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/typical/type.rb', line 3

def self.of(object)
  case object
  when Type
    object
  when ::Hash
    Hash.new(object)
  when ::Array
    Array.new(object)
  when ::Set
    Set.new(object)
  when Class
    if object == ::Hash
      Hash.new
    elsif object == ::Array
      Array.new
    elsif object == ::Set
      Set.new
    else
      new(object)
    end
  else
    new(object.class)
  end
end

Instance Method Details

#==(other) ⇒ Object



39
40
41
# File 'lib/typical/type.rb', line 39

def ==(other)
  other.is_a?(Type) && type == other.type
end

#eql?(other) ⇒ Boolean

Returns:

  • (Boolean)


43
44
45
# File 'lib/typical/type.rb', line 43

def eql?(other)
  self == other
end

#hashObject



47
48
49
# File 'lib/typical/type.rb', line 47

def hash
  type.hash
end

#inspectObject



68
69
70
# File 'lib/typical/type.rb', line 68

def inspect
  "#<Type:#{type}>"
end

#normalizeObject



60
61
62
# File 'lib/typical/type.rb', line 60

def normalize
  self
end

#nullable?Boolean

Returns:

  • (Boolean)


56
57
58
# File 'lib/typical/type.rb', line 56

def nullable?
  types.any? { |type| type.type == NilClass }
end

#prominent_typeObject



64
65
66
# File 'lib/typical/type.rb', line 64

def prominent_type
  self
end

#typesObject

This makes Type and Type::Union duck-typable



35
36
37
# File 'lib/typical/type.rb', line 35

def types
  ::Set.new([self])
end

#|(other) ⇒ Object

Raises:

  • (TypeError)


51
52
53
54
# File 'lib/typical/type.rb', line 51

def |(other)
  raise TypeError, "Can only make a union of Type and subclasses of Type" unless other.is_a?(Type)
  other.is_a?(Union) ? (other | self) : Union.new([self, other])
end