Browse files

Add nodes for boolean constants

This is useful for dynamically created predicates e.g:

expr1 = table.create_false
expr2 = table.create_false

expr1 = create_a_predicate() if some_condition
expr2 = create_another_predicate() if some_other_condition

table.where(expr1.and(expr2))
  • Loading branch information...
1 parent c9517c1 commit 11f929b5c485adab60ea2d8b515ef2abcf5400f4 @dcadenas dcadenas committed May 31, 2011
View
8 lib/arel/factory_methods.rb
@@ -2,6 +2,14 @@ module Arel
###
# Methods for creating various nodes
module FactoryMethods
+ def create_true
+ Arel::Nodes::True.new
+ end
+
+ def create_false
+ Arel::Nodes::False.new
+ end
+
def create_table_alias relation, name
Nodes::TableAlias.new(relation, name)
end
View
2 lib/arel/nodes.rb
@@ -8,6 +8,8 @@
# terminal
require 'arel/nodes/terminal'
+require 'arel/nodes/true'
+require 'arel/nodes/false'
# unary
require 'arel/nodes/unary'
View
17 lib/arel/nodes/false.rb
@@ -0,0 +1,17 @@
+module Arel
+ module Nodes
+ class False < Arel::Nodes::Node
+ def not
+ True.new
+ end
+
+ def or right
+ right
+ end
+
+ def and right
+ self
+ end
+ end
+ end
+end
View
17 lib/arel/nodes/true.rb
@@ -0,0 +1,17 @@
+module Arel
+ module Nodes
+ class True < Arel::Nodes::Node
+ def not
+ False.new
+ end
+
+ def or right
+ self
+ end
+
+ def and right
+ right
+ end
+ end
+ end
+end
View
1 lib/arel/predications.rb
@@ -1,6 +1,5 @@
module Arel
module Predications
-
def not_eq other
Nodes::NotEqual.new self, other
end
View
8 lib/arel/visitors/to_sql.rb
@@ -90,6 +90,14 @@ def visit_Arel_Nodes_Exists o
o.alias ? " AS #{visit o.alias}" : ''}"
end
+ def visit_Arel_Nodes_True o
+ "TRUE"
+ end
+
+ def visit_Arel_Nodes_False o
+ "FALSE"
+ end
+
def table_exists? name
@pool.table_exists? name
end
View
10 test/test_factory_methods.rb
@@ -23,6 +23,16 @@ def test_create_on
assert_equal :one, on.expr
end
+ def test_create_true
+ true_node = @factory.create_true
+ assert_instance_of Nodes::True, true_node
+ end
+
+ def test_create_false
+ false_node = @factory.create_false
+ assert_instance_of Nodes::False, false_node
+ end
+
def test_lower
lower = @factory.lower :one
assert_instance_of Nodes::NamedFunction, lower
View
16 test/visitors/test_to_sql.rb
@@ -325,6 +325,22 @@ def quote value, column = nil
end
end
+ describe 'Constants' do
+ it "should handle true" do
+ test = Table.new(:users).create_true
+ @visitor.accept(test).must_be_like %{
+ TRUE
+ }
+ end
+
+ it "should handle false" do
+ test = Table.new(:users).create_false
+ @visitor.accept(test).must_be_like %{
+ FALSE
+ }
+ end
+ end
+
describe 'TableAlias' do
it "should use the underlying table for checking columns" do
test = Table.new(:users).alias('zomgusers')[:id].eq '3'

0 comments on commit 11f929b

Please sign in to comment.