Class: Typespec::Struct

Inherits:
Object
  • Object
show all
Defined in:
lib/typespec.rb

Overview

Direct Known Subclasses

Object

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*properties, **properties_with_spec) ⇒ Struct

Returns a new instance of Struct.



128
129
130
131
132
133
134
135
136
# File 'lib/typespec.rb', line 128

def initialize(*properties, **properties_with_spec)
  if !properties.empty?
    @properties = Hash[properties.map{|name| [name, Typespec.anything]}]
  elsif properties_with_spec
    @properties = properties_with_spec
  else
    @properties = {}
  end
end

Class Method Details

.[](*properties, **properties_with_spec) ⇒ Object



138
139
140
# File 'lib/typespec.rb', line 138

def self.[](*properties, **properties_with_spec)
  Typespec::Struct.new(*properties, **properties_with_spec)
end

Instance Method Details

#valid?(struct, opts = {}) ⇒ Boolean

Returns:

  • (Boolean)


142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
# File 'lib/typespec.rb', line 142

def valid?(struct, opts={})
  if struct.is_a? ::Struct
    ignore_if_not_in_spec = opts.fetch(:ignore_if_not_in_spec, false)
    struct.instance_variables.all? do |property|
      undecorated = property.to_s[1..-1].to_sym
      if @properties.include?(undecorated)
        value = struct.instance_variable_get(property)
        @properties[undecorated].valid?(value)
      else
        ignore_if_not_in_spec
      end
    end
  else
    false
  end
end