aboutsummaryrefslogtreecommitdiffstats
path: root/lib/active_relation/relations/rename.rb
blob: c9c47f95b835d8b9c7cf1a6642577708486a13be (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
module ActiveRelation
  class Rename < Compound
    attr_reader :autonym, :pseudonym

    def initialize(relation, pseudonyms)
      @autonym, @pseudonym = pseudonyms.shift
      @relation = pseudonyms.empty?? relation : Rename.new(relation, pseudonyms)
    end

    def ==(other)
      relation == other.relation and autonym == other.autonym and pseudonym == other.pseudonym
    end

    def qualify
      Rename.new(relation.qualify, autonym.qualify => self.pseudonym)
    end

    protected
    def projections
      relation.send(:projections).collect(&method(:substitute))
    end
    
    def attribute(name)
      case
      when name == pseudonym then autonym.as(pseudonym)
      when relation[name] == autonym then nil
      else relation[name]
      end
    end

    private
    def substitute(attribute)
      attribute == autonym ? attribute.as(pseudonym) : attribute
    end
  end
end