aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/lib/arel/nodes/case.rb
blob: 1c4b727bf63e4fbcefe6c2a520d1b5c189e2944c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# frozen_string_literal: true

module Arel # :nodoc: all
  module Nodes
    class Case < Arel::Nodes::NodeExpression
      attr_accessor :case, :conditions, :default

      def initialize(expression = nil, default = nil)
        @case = expression
        @conditions = []
        @default = default
      end

      def when(condition, expression = nil)
        @conditions << When.new(Nodes.build_quoted(condition), expression)
        self
      end

      def then(expression)
        @conditions.last.right = Nodes.build_quoted(expression)
        self
      end

      def else(expression)
        @default = Else.new Nodes.build_quoted(expression)
        self
      end

      def initialize_copy(other)
        super
        @case = @case.clone if @case
        @conditions = @conditions.map { |x| x.clone }
        @default = @default.clone if @default
      end

      def hash
        [@case, @conditions, @default].hash
      end

      def eql?(other)
        self.class == other.class &&
          self.case == other.case &&
          self.conditions == other.conditions &&
          self.default == other.default
      end
      alias :== :eql?
    end

    class When < Binary # :nodoc:
    end

    class Else < Unary # :nodoc:
    end
  end
end