aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorJoshua Cody <josh@joshuacody.net>2014-07-26 22:27:31 -0500
committerJoshua Cody <josh@joshuacody.net>2014-07-26 22:27:31 -0500
commitbb8416d0943f3e797d572d127a2d74103761d947 (patch)
tree2d0d4101c213cb4d892d244091515dbb6fc2c103
parent66cee768bc163537087037a583f60639eae49fc3 (diff)
downloadrails-bb8416d0943f3e797d572d127a2d74103761d947.tar.gz
rails-bb8416d0943f3e797d572d127a2d74103761d947.tar.bz2
rails-bb8416d0943f3e797d572d127a2d74103761d947.zip
Allow for alias omission in aggregate expressions
-rw-r--r--lib/arel/expressions.rb23
-rw-r--r--test/test_expressions.rb29
2 files changed, 44 insertions, 8 deletions
diff --git a/lib/arel/expressions.rb b/lib/arel/expressions.rb
index fa18f15b67..717cf412ee 100644
--- a/lib/arel/expressions.rb
+++ b/lib/arel/expressions.rb
@@ -4,24 +4,31 @@ module Arel
Nodes::Count.new [self], distinct
end
- def sum
- Nodes::Sum.new [self], Nodes::SqlLiteral.new('sum_id')
+ def sum(alias_as = "sum_id")
+ Nodes::Sum.new [self], node_alias(alias_as)
end
- def maximum
- Nodes::Max.new [self], Nodes::SqlLiteral.new('max_id')
+ def maximum(alias_as = "max_id")
+ Nodes::Max.new [self], node_alias(alias_as)
end
- def minimum
- Nodes::Min.new [self], Nodes::SqlLiteral.new('min_id')
+ def minimum(alias_as = "min_id")
+ Nodes::Min.new [self], node_alias(alias_as)
end
- def average
- Nodes::Avg.new [self], Nodes::SqlLiteral.new('avg_id')
+ def average(alias_as = "avg_id")
+ Nodes::Avg.new [self], node_alias(alias_as)
end
def extract field
Nodes::Extract.new [self], field
end
+
+ private
+
+ def node_alias(alias_as)
+ alias_as.nil? ? nil : Nodes::SqlLiteral.new(alias_as)
+ end
+
end
end
diff --git a/test/test_expressions.rb b/test/test_expressions.rb
new file mode 100644
index 0000000000..d061bbc335
--- /dev/null
+++ b/test/test_expressions.rb
@@ -0,0 +1,29 @@
+require 'helper'
+
+module Arel
+ describe "Expressions" do
+ before do
+ @table = Table.new(:users)
+ end
+
+ describe "average" do
+ it "aliases the average as avg_id by default" do
+ @table[:score].average.to_sql.must_be_like %{
+ AVG("users"."score") AS avg_id
+ }
+ end
+
+ it "aliases the average as another string" do
+ @table[:score].average("my_alias").to_sql.must_be_like %{
+ AVG("users"."score") AS my_alias
+ }
+ end
+
+ it "omits the alias if nil" do
+ @table[:score].average(nil).to_sql.must_be_like %{
+ AVG("users"."score")
+ }
+ end
+ end
+ end
+end