Skip to content

Commit

Permalink
create a real table alias
Browse files Browse the repository at this point in the history
  • Loading branch information
kronn committed May 20, 2011
1 parent 58c3d1d commit eb6dba2
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
7 changes: 6 additions & 1 deletion lib/arel/table.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ class Table
@engine = nil
class << self; attr_accessor :engine; end

attr_accessor :name, :engine, :aliases, :table_alias
attr_accessor :name, :engine, :aliases, :table_alias, :options

# TableAlias and Table both have a #table_name which is the name of the underlying table
alias :table_name :name
Expand All @@ -18,6 +18,7 @@ def initialize name, engine = Table.engine
@aliases = []
@table_alias = nil
@primary_key = nil
@options = (Hash === engine) ? engine : {}

if Hash === engine
@engine = engine[:engine] || Table.engine
Expand Down Expand Up @@ -48,6 +49,10 @@ def alias name = "#{self.name}_2"
end
end

def as table_alias
Table.new(name, options.merge(:as => table_alias))
end

def from table
SelectManager.new(@engine, table)
end
Expand Down
17 changes: 17 additions & 0 deletions test/test_table.rb
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,23 @@ module Arel
end
end

describe 'as' do
it 'should create a node that is like the original table' do
@relation.must_respond_to(:as)

node = @relation.as(:foo)
node.must_be_kind_of(Table)
node.name.must_equal 'users'
node.table_alias.to_sym.to_s.must_equal 'foo'

node.wont_equal @relation

# this tries to compare the columns by name in order to verify that the tables are the same
col_name = lambda { |col| col.name }
node.columns.map(&col_name).must_equal @relation.columns.map(&col_name)
end
end

describe 'new' do
it 'should accept an engine' do
rel = Table.new :users, 'foo'
Expand Down

0 comments on commit eb6dba2

Please sign in to comment.