Class: MaimaiNet::Model::Base::Struct

Inherits:
Struct
  • Object
show all
Defined in:
lib/maimai_net/model.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(**kwargs) ⇒ Struct

Returns a new instance of Struct.

Parameters:

  • kwargs (Hash)

    options are strong-typed based on class definition



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/maimai_net/model.rb', line 10

def initialize(**kwargs)
  props = self.class.instance_variable_get(:@_properties)
  keys = props.keys
  optional_keys = props.select do |k, pr|
    Either === pr[:class] &&
    pr[:class].variants.include?(NilClass)
  end.keys

  missing_keys = keys - (kwargs.keys | optional_keys)
  fail KeyError, "#{missing_keys.join(', ')} is not defined for #{self.class}" unless missing_keys.empty?
  kwargs.each do |key, value|
    fail KeyError, "#{key} is not defined as struct member" unless keys.include?(key)
    class_str = value.respond_to?(:map_class) ? value.map_class : value.class
    fail TypeError, "#{key} type mismatch, given #{class_str}, expected #{props[key][:class]}" unless props[key][:class] === value
  end

  args = kwargs.values_at(*keys)
  super(*args)
end

Class Method Details

.new(**opts, &block) ⇒ Struct

creates a strong-typed struct data

Parameters:

  • opts (Hash{Symbol => Module})

    list of struct members along with respective type definition

Returns:

  • (Struct)

    new subclass with defined types



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/maimai_net/model.rb', line 35

def new(**opts, &block)
  super(*opts.keys) do
    @_properties = {}
    opts.each do |key, typedata|
      @_properties[key] = case typedata
                          when Array
                            {class: Generic[*typedata]}
                          when Module, Variant
                            {class: typedata}
                          else
                            fail TypeError, "invalid type definition"
                          end
    end

    class_exec(&block) if block_given?
  end
end