Sha256: 5e121810e1a113bd26e6526215dd7d309311513a7d063d4727f7c11adc654443

Contents?: true

Size: 1.33 KB

Versions: 12

Compression:

Stored size: 1.33 KB

Contents

require "query_helper/sql_parser"

class QueryHelper
  class ColumnMap

    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

    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

    attr_accessor :alias_name, :sql_expression, :aggregate

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

  end
end

Version data entries

12 entries across 12 versions & 1 rubygems

Version Path
query_helper-0.4.0 lib/query_helper/column_map.rb
query_helper-0.3.8 lib/query_helper/column_map.rb
query_helper-0.3.6 lib/query_helper/column_map.rb
query_helper-0.3.5 lib/query_helper/column_map.rb
query_helper-0.3.4 lib/query_helper/column_map.rb
query_helper-0.2.29 lib/query_helper/column_map.rb
query_helper-0.2.30 lib/query_helper/column_map.rb
query_helper-0.2.28 lib/query_helper/column_map.rb
query_helper-0.2.26 lib/query_helper/column_map.rb
query_helper-0.2.21 lib/query_helper/column_map.rb
query_helper-0.2.20 lib/query_helper/column_map.rb
query_helper-0.2.19 lib/query_helper/column_map.rb