Class: QueryHelper::ColumnMap

Inherits:
Object
  • Object
show all
Defined in:
lib/query_helper/column_map.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(alias_name:, sql_expression:, aggregate: false) ⇒ ColumnMap

Returns a new instance of ColumnMap.



45
46
47
48
49
50
51
52
53
# File 'lib/query_helper/column_map.rb', line 45

def initialize(
  alias_name:,
  sql_expression:,
  aggregate: false
)
  @alias_name = alias_name
  @sql_expression = sql_expression
  @aggregate = aggregate
end

Instance Attribute Details

#aggregateObject

Returns the value of attribute aggregate.



43
44
45
# File 'lib/query_helper/column_map.rb', line 43

def aggregate
  @aggregate
end

#alias_nameObject

Returns the value of attribute alias_name.



43
44
45
# File 'lib/query_helper/column_map.rb', line 43

def alias_name
  @alias_name
end

#sql_expressionObject

Returns the value of attribute sql_expression.



43
44
45
# File 'lib/query_helper/column_map.rb', line 43

def sql_expression
  @sql_expression
end

Class Method Details

.create_column_mappings(custom_mappings:, query:, model:) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/query_helper/column_map.rb', line 6

def self.create_column_mappings(custom_mappings:, query:, model:)
  parser = SqlParser.new(query)
  maps = create_from_hash(custom_mappings)

  parser.find_aliases.each do |m|
    maps << m if maps.select{|x| x.alias_name == m.alias_name}.empty?
  end

  model.attribute_names.each do |attribute|
    if maps.select{|x| x.alias_name == attribute}.empty?
      maps << ColumnMap.new(alias_name: attribute, sql_expression: "#{model.table_name.pluralize}.#{attribute}")
    end
  end

  maps
end

.create_from_hash(hash) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/query_helper/column_map.rb', line 23

def self.create_from_hash(hash)
  map = []
  hash.each do |k,v|
    alias_name = k
    aggregate = false
    if v.class == String
      sql_expression = v
    elsif v.class == Hash
      sql_expression = v[:sql_expression]
      aggregate = v[:aggregate]
    end
    map << self.new(
      alias_name: alias_name,
      sql_expression: sql_expression,
      aggregate: aggregate
    )
  end
  map
end