Class: Dry::Data::Type

Inherits:
Object
  • Object
show all
Defined in:
lib/dry/data/type.rb,
lib/dry/data/type/enum.rb,
lib/dry/data/type/hash.rb,
lib/dry/data/type/array.rb,
lib/dry/data/type/constrained.rb

Direct Known Subclasses

Array, Constrained, Hash

Defined Under Namespace

Classes: Array, Constrained, Enum, Hash

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(constructor, primitive) ⇒ Type

Returns a new instance of Type.



56
57
58
59
# File 'lib/dry/data/type.rb', line 56

def initialize(constructor, primitive)
  @constructor = constructor
  @primitive = primitive
end

Instance Attribute Details

#constructorObject (readonly)

Returns the value of attribute constructor.



11
12
13
# File 'lib/dry/data/type.rb', line 11

def constructor
  @constructor
end

#primitiveObject (readonly)

Returns the value of attribute primitive.



12
13
14
# File 'lib/dry/data/type.rb', line 12

def primitive
  @primitive
end

Class Method Details

.[](primitive) ⇒ Object



34
35
36
37
38
39
40
41
42
# File 'lib/dry/data/type.rb', line 34

def self.[](primitive)
  if primitive == ::Array
    Type::Array
  elsif primitive == ::Hash
    Type::Hash
  else
    Type
  end
end

.passthrough_constructor(input) ⇒ Object



52
53
54
# File 'lib/dry/data/type.rb', line 52

def self.passthrough_constructor(input)
  input
end

.strict_constructor(primitive, input) ⇒ Object



44
45
46
47
48
49
50
# File 'lib/dry/data/type.rb', line 44

def self.strict_constructor(primitive, input)
  if input.is_a?(primitive)
    input
  else
    raise TypeError, "#{input.inspect} has invalid type"
  end
end

Instance Method Details

#call(input) ⇒ Object Also known as: []



73
74
75
# File 'lib/dry/data/type.rb', line 73

def call(input)
  constructor[input]
end

#constrained(options) ⇒ Object



30
31
32
# File 'lib/dry/data/type/constrained.rb', line 30

def constrained(options)
  Constrained.new(constructor, primitive, Data.Rule(primitive, options))
end

#enum(*values) ⇒ Object



61
62
63
# File 'lib/dry/data/type.rb', line 61

def enum(*values)
  Enum.new(values, constrained(inclusion: values))
end

#nameObject



69
70
71
# File 'lib/dry/data/type.rb', line 69

def name
  primitive.name
end

#optionalObject



65
66
67
# File 'lib/dry/data/type.rb', line 65

def optional
  Optional.new(Data['nil'] | self)
end

#valid?(input) ⇒ Boolean

Returns:

  • (Boolean)


78
79
80
# File 'lib/dry/data/type.rb', line 78

def valid?(input)
  input.is_a?(primitive)
end

#|(other) ⇒ Object



82
83
84
# File 'lib/dry/data/type.rb', line 82

def |(other)
  SumType.new(self, other)
end