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

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

    def ==(other)
      self.class == other.class and
      relation   == other.relation and
      attribute  == other.attribute and
      pseudonym  == other.pseudonym
    end

    def qualify
      Rename.new(relation.qualify, attribute.qualify => pseudonym)
    end
    
    def attributes
      relation.attributes.collect(&method(:baptize))
    end
    
    private
    def baptize(attribute)
      (attribute =~ self.attribute ? attribute.as(pseudonym) : attribute).bind(self) rescue nil
    end
  end
end