Class: NRSER::Types::Shape

Inherits:
Type show all
Defined in:
lib/nrser/types/shape.rb

Overview

Note:

Construct shape types using the Shape factory.

Create a Shape type that parameterizes #pairs of object keys and Type values.

Members of the type are values ‘v` for which for all keys `k` and paired value types `t_k` `v` is a member of `t_k`:

shape.pairs.all? { |k, t_k| t_k.test? v[k] }

Instance Attribute Summary collapse

Display Instance Methods collapse

Instance Method Summary collapse

Methods inherited from Type

#===, #builtin_inspect, #check, #check!, #default_name, #from_data, #from_s, #has_from_s?, #has_to_data?, #inspect, #intersection, #name, #not, #respond_to?, #symbolic, #test, #to_data, #to_proc, #to_s, #union, #xor

Constructor Details

#initialize(pairs, **options) ⇒ Shape

Instantiate a new ‘NRSER::Types::Shape`.



51
52
53
54
55
56
# File 'lib/nrser/types/shape.rb', line 51

def initialize pairs, **options
  super **options
  @pairs = pairs.map { |k, v|
    [k, NRSER::Types.make( v )]
  }.to_h.freeze
end

Instance Attribute Details

#pairsHash (readonly)

TODO document ‘pairs` attribute.

Returns:



44
45
46
# File 'lib/nrser/types/shape.rb', line 44

def pairs
  @pairs
end

Instance Method Details

#custom_from_data(data) ⇒ Object



108
109
110
111
112
# File 'lib/nrser/types/shape.rb', line 108

def custom_from_data data
  pairs.map { |key, type|
    [ key, type.from_data( data[key] ) ]
  }.to_h
end

#default_symbolicObject



91
92
93
# File 'lib/nrser/types/shape.rb', line 91

def default_symbolic
  string_format pre: '{', post: '}', method: :symbolic
end

#explainObject



96
97
98
# File 'lib/nrser/types/shape.rb', line 96

def explain
  string_format pre: 'Shape<', post: '>', method: :explain
end

#has_from_data?Boolean

Returns:



103
104
105
# File 'lib/nrser/types/shape.rb', line 103

def has_from_data?
  pairs.values.all? { |type| type.has_from_data? }
end

#string_format(pre:, post:, method:, spaces: true) ⇒ Object




74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/nrser/types/shape.rb', line 74

def string_format pre:, post:, method:, spaces: true
  space = spaces ? ' ' : ''

  inner = @pairs.map { |k, v|
    key_part = if k.is_a? Symbol
      "#{ k }:#{ space }"
    else
      "#{ k.inspect }#{ space }=>#{ space }"
    end

    key_part + v.public_send( method )
  }

  pre + inner.join( ",#{ space }" ) + post
end

#test?(value) ⇒ Boolean

Instance Methods

Returns:



62
63
64
65
66
67
68
# File 'lib/nrser/types/shape.rb', line 62

def test? value
  begin
    @pairs.all? { |k, v| v === value[k] }
  rescue
    false
  end
end