Class: Babik::QuerySet::Projection

Inherits:
Object
  • Object
show all
Defined in:
lib/babik/queryset/components/projection.rb

Overview

Manages the projection of a SELECT QuerySet

Instance Method Summary collapse

Constructor Details

#initialize(model, fields) ⇒ Projection

Constructs a projection

Parameters:

  • model (ActiveRecord::Base)

    model the projection is based on.

  • fields (Array)

    array of fields that will be projected.



15
16
17
18
19
20
21
22
23
# File 'lib/babik/queryset/components/projection.rb', line 15

def initialize(model, fields)
  @fields = []
  @fields_hash = {}
  fields.each do |field|
    new_field = ProjectedField.new(model, field)
    @fields << new_field
    @fields_hash[new_field.alias.to_sym] = new_field
  end
end

Instance Method Details

#apply_transforms(result_set) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/babik/queryset/components/projection.rb', line 25

def apply_transforms(result_set)
  result_set.map do |record|
    record.symbolize_keys!
    transformed_record = {}
    record.each do |field, value|
      transform = @fields_hash[field].transform
      transformed_record[field] = if transform
                                    transform.call(value)
                                  else
                                    value
                                  end
    end
    transformed_record
  end
end

#sqlSQL

Return sql of the fields to project. Does not include SELECT.

Returns:

  • (SQL)

    SQL code for fields to select in SELECT.



44
45
46
# File 'lib/babik/queryset/components/projection.rb', line 44

def sql
  @fields.map(&:sql).join(', ')
end