Module: SorbetRails::PluckToTStruct

Extended by:
T::Sig
Defined in:
lib/sorbet-rails/rails_mixins/pluck_to_tstruct.rb

Defined Under Namespace

Classes: UnexpectedAssociations, UnexpectedType

Constant Summary collapse

NILCLASS_STRING =
"NilClass".freeze

Instance Method Summary collapse

Instance Method Details

#pluck_to_tstruct(ta_struct, associations: {}) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/sorbet-rails/rails_mixins/pluck_to_tstruct.rb', line 17

def pluck_to_tstruct(ta_struct, associations: {})
  tstruct = ta_struct.get_type

  if !(tstruct < T::Struct)
    raise UnexpectedType.new("pluck_to_tstruct expects a tstruct subclass, given #{tstruct}")
  end

  tstruct_props = tstruct.props
  tstruct_keys = tstruct_props.keys
  associations_keys = associations.keys
  invalid_keys = associations_keys - tstruct_keys

  if invalid_keys.any?
    raise UnexpectedAssociations.new("Argument 'associations' contains keys that don't exist in #{tstruct}: #{invalid_keys.join(", ")}")
  end

  pluck_keys = (tstruct_keys - associations_keys) + associations.values

  # loosely based on pluck_to_hash gem
  # https://github.com/girishso/pluck_to_hash/blob/master/lib/pluck_to_hash.rb
  keys_one = pluck_keys.size == 1
  pluck(*pluck_keys).map do |row|
    row = [row] if keys_one
    value = Hash[map_nil_values_to_default(tstruct_props, tstruct_keys.zip(row))]
    tstruct.new(value)
  end
end