aboutsummaryrefslogtreecommitdiffstats
path: root/lib/active_relation/relations/rename.rb
blob: c7b99c2127c39218ff95127021a8fa905264f0cf (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 :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 == 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] == schmattribute then nil
        else relation[name]
        end
      end
  
      private
      def substitute(a)
        a == schmattribute ? a.alias(self.alias) : a
      end
    end
  end
end