Sha256: 5434c40f0a0474d0fd5bb1054f279356e1144c9e9d7ee8e714cc824efc0b708c
Contents?: true
Size: 1.02 KB
Versions: 1
Compression:
Stored size: 1.02 KB
Contents
module RelationToStruct::ActiveRecordRelationExtension extend ::ActiveSupport::Concern 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 end ::ActiveRecord::Relation.send(:include, RelationToStruct::ActiveRecordRelationExtension)
Version data entries
1 entries across 1 versions & 1 rubygems
Version | Path |
---|---|
relation_to_struct-1.4.0 | lib/relation_to_struct/active_record_relation_extension.rb |