Sha256: d57639a50aafcc09e175500544b81b62de87716287d9219a0177912ccd383557

Contents?: true

Size: 816 Bytes

Versions: 13

Compression:

Stored size: 816 Bytes

Contents

# typed: false
require 'sorbet-runtime'

module SorbetRails::PluckToTStruct
  extend T::Sig
  sig {
    type_parameters(:U).
    params(
      ta_struct: ITypeAssert[T.type_parameter(:U)],
    ).
    returns(T::Array[T.type_parameter(:U)])
  }
  def pluck_to_tstruct(ta_struct)
    tstruct = ta_struct.get_type
  
    if !(tstruct < T::Struct)
      raise UnexpectedType.new("pluck_to_tstruct expects a tstruct subclass, given #{tstruct}")
    end

    keys = tstruct.props.keys

    # loosely based on pluck_to_hash gem
    # https://github.com/girishso/pluck_to_hash/blob/master/lib/pluck_to_hash.rb
    keys_one = keys.size == 1
    pluck(*keys).map do |row|
      row = [row] if keys_one
      value = Hash[keys.zip(row)]
      tstruct.new(value)
    end
  end
  
  class UnexpectedType < StandardError; end
end

Version data entries

13 entries across 13 versions & 1 rubygems

Version Path
sorbet-rails-0.7.0 lib/sorbet-rails/rails_mixins/pluck_to_tstruct.rb
sorbet-rails-0.6.5.1 lib/sorbet-rails/rails_mixins/pluck_to_tstruct.rb
sorbet-rails-0.6.5 lib/sorbet-rails/rails_mixins/pluck_to_tstruct.rb
sorbet-rails-0.6.4 lib/sorbet-rails/rails_mixins/pluck_to_tstruct.rb
sorbet-rails-0.6.3 lib/sorbet-rails/rails_mixins/pluck_to_tstruct.rb
sorbet-rails-0.6.2 lib/sorbet-rails/rails_mixins/pluck_to_tstruct.rb
sorbet-rails-0.6.1 lib/sorbet-rails/rails_mixins/pluck_to_tstruct.rb
sorbet-rails-0.6.0 lib/sorbet-rails/rails_mixins/pluck_to_tstruct.rb
sorbet-rails-0.5.9.1 lib/sorbet-rails/rails_mixins/pluck_to_tstruct.rb
sorbet-rails-0.5.9 lib/sorbet-rails/rails_mixins/pluck_to_tstruct.rb
sorbet-rails-0.5.8.1 lib/sorbet-rails/rails_mixins/pluck_to_tstruct.rb
sorbet-rails-0.5.8 lib/sorbet-rails/rails_mixins/pluck_to_tstruct.rb
sorbet-rails-0.5.7 lib/sorbet-rails/rails_mixins/pluck_to_tstruct.rb