123456789_123456789_123456789_123456789_123456789_

Class: ActiveRecord::Calculations::ColumnAliasTracker

Do not use. This class is for internal use only.
Relationships & Source Files
Inherits: Object
Defined in: activerecord/lib/active_record/relation/calculations.rb

Class Method Summary

Instance Method Summary

Constructor Details

.new(connection) ⇒ ColumnAliasTracker

[ GitHub ]

  
# File 'activerecord/lib/active_record/relation/calculations.rb', line 9

def initialize(connection)
  @connection = connection
  @aliases = Hash.new(0)
end

Instance Method Details

#alias_for(field)

[ GitHub ]

  
# File 'activerecord/lib/active_record/relation/calculations.rb', line 14

def alias_for(field)
  aliased_name = column_alias_for(field)

  if @aliases[aliased_name] == 0
    @aliases[aliased_name] = 1
    aliased_name
  else
    # Update the count
    count = @aliases[aliased_name] += 1
    "#{truncate(aliased_name)}_#{count}"
  end
end

#column_alias_for(field) (private)

Converts the given field to the value that the database adapter returns as a usable column name:

column_alias_for("users.id")                 # => "users_id"
column_alias_for("sum(id)")                  # => "sum_id"
column_alias_for("count(distinct users.id)") # => "count_distinct_users_id"
column_alias_for("count(*)")                 # => "count_all"
[ GitHub ]

  
# File 'activerecord/lib/active_record/relation/calculations.rb', line 35

def column_alias_for(field)
  column_alias = +field
  column_alias.gsub!(/\*/, "all")
  column_alias.gsub!(/\W+/, " ")
  column_alias.strip!
  column_alias.gsub!(/ +/, "_")
  @connection.table_alias_for(column_alias)
end

#truncate(name) (private)

[ GitHub ]

  
# File 'activerecord/lib/active_record/relation/calculations.rb', line 44

def truncate(name)
  name.slice(0, @connection.table_alias_length - 2)
end