aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/lib/active_record/connection_adapters/postgresql/oid/rails_5_1_point.rb
blob: 4da240edb2af22e073db1a1912831e5e8670dfae (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
45
46
47
48
49
50
51
52
module ActiveRecord
  Point = Struct.new(:x, :y)

  module ConnectionAdapters
    module PostgreSQL
      module OID # :nodoc:
        class Rails51Point < Type::Value # :nodoc:
          include Type::Helpers::Mutable

          def type
            :point
          end

          def cast(value)
            case value
            when ::String
              return if value.blank?
              
              if value[0] == '(' && value[-1] == ')'
                value = value[1...-1]
              end
              x, y = value.split(",")
              build_point(x, y)
            when ::Array
              build_point(*value)
            else
              value
            end
          end

          def serialize(value)
            if value.is_a?(ActiveRecord::Point)
              "(#{number_for_point(value.x)},#{number_for_point(value.y)})"
            else
              super
            end
          end

          private

          def number_for_point(number)
            number.to_s.gsub(/\.0$/, '')
          end

          def build_point(x, y)
            ActiveRecord::Point.new(Float(x), Float(y))
          end
        end
      end
    end
  end
end