Module: RelationToStruct::ActiveRecordRelationExtension

Defined in:
lib/relation_to_struct/active_record_relation_extension.rb

Instance Method Summary collapse

Instance Method Details

#to_structs(struct_class) ⇒ Object

Raises:

  • (ArgumentError)


2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/relation_to_struct/active_record_relation_extension.rb', line 2

def to_structs(struct_class)
  raise ArgumentError, 'Expected select_values to be present' unless self.select_values.present?

  relation = spawn

  # See the definition of #pluck in:
  # activerecord/lib/active_record/relation/calculations.rb
  result = klass.connection.select_all(relation.arel)

  if result.columns.size != struct_class.members.size
    raise ArgumentError, 'Expected struct fields and columns lengths to be equal'
  end

  if result.columns.size != result.columns.uniq.size
    raise ArgumentError, 'Expected column names to be unique'
  end

  values_after_casting = result.cast_values()

  if result.columns.size == 1
    values_after_casting.map do |tuple|
      struct_class.new(tuple)
    end
  else
    values_after_casting.map do |tuple|
      struct_class.new(*tuple)
    end
  end
end