aboutsummaryrefslogtreecommitdiffstats
path: root/lib/active_relation/relations/rename.rb
blob: 7a1693df579e666e806f66151df2d6a2e1b1f81d (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
module ActiveRelation
  module Relations
    class Rename < Compound
      attr_reader :relation, :schmattribute, :alias
  
      def initialize(relation, renames)
        @schmattribute, @alias = renames.shift
        @relation = renames.empty?? relation : Rename.new(relation, renames)
      end
  
      def ==(other)
        relation == other.relation and schmattribute.eql?(other.schmattribute) and self.alias == other.alias
      end
  
      def attributes
        relation.attributes.collect { |a| substitute(a) }
      end
  
      def qualify
        Rename.new(relation.qualify, schmattribute.qualify => self.alias)
      end
  
      protected
      def attribute(name)
        case
        when name == self.alias then schmattribute.alias(self.alias)
        when relation[name].eql?(schmattribute) then nil
        else relation[name]
        end
      end
  
      private
      def substitute(a)
        a.eql?(schmattribute) ? a.alias(self.alias) : a
      end
    end
  end
end