aboutsummaryrefslogtreecommitdiffstats
path: root/lib/active_relation/relations/rename.rb
blob: 8d92e9422cdc5946de93e54f09881c97d6e43e98 (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
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(:substitute))
    end
    
    protected
    def attribute_for_name(name)
      case
      when referring_by_autonym?(name) then nil
      when referring_by_pseudonym?(name) then substitute(relation[attribute])
      else relation[name].substitute(self) rescue nil
      end
    end

    private
    def substitute(attribute)
      (attribute =~ self.attribute ? attribute.as(pseudonym) : attribute).substitute(self) rescue nil
    end

    def referring_by_autonym?(name)
      relation[name] == relation[attribute]
    end
    
    def referring_by_pseudonym?(name)
      name == pseudonym
    end
  end
end