aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/lib/active_record/attributes/aliasing.rb
blob: db77739d1f5c846d4b9881d96097b82da2c7ee06 (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
module ActiveRecord
  module Attributes
    module Aliasing
      # Allows access to keys using aliased names.
      #
      # Example:
      # class Attributes < Hash
      #   include Aliasing
      # end
      #
      # attributes = Attributes.new
      # attributes.aliases['id'] = 'fancy_primary_key'
      # attributes['fancy_primary_key'] = 2020
      #
      # attributes['id']
      # => 2020
      #
      # Additionally, symbols are always aliases of strings:
      # attributes[:fancy_primary_key]
      # => 2020
      #
      def [](key)
        super(unalias(key))
      end

      def []=(key, value)
        super(unalias(key), value)
      end

      def aliases
        @aliases ||= {}
      end

      def unalias(key)
        key = key.to_s
        aliases[key] || key
      end

    end
  end
end