From 9f4a3fd7383d1fa5e96030c411a998b89f510476 Mon Sep 17 00:00:00 2001 From: Sean Griffin Date: Fri, 5 Jun 2015 09:02:25 -0600 Subject: Return a `Point` object from the PG Point type This introduces a deprecation cycle to change the behavior of the default point type in the PostgreSQL adapter. The old behavior will continue to be available for the immediate future as `:legacy_point`. The current behavior of returning an `Array` causes several problems, the most significant of which is that we cannot differentiate between an array of points, and a point itself in the case of a column with the `point[]` type. The attributes API gives us a reasonable way to have a proper deprecation cycle for this change, so let's take advantage of it. If we like this change, we can also add proper support for the other geometric types (line, lseg, box, path, polygon, and circle), all of which are just aliases for string today. Fixes #20441 --- .../postgresql/oid/rails_5_1_point.rb | 50 ++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 activerecord/lib/active_record/connection_adapters/postgresql/oid/rails_5_1_point.rb (limited to 'activerecord/lib/active_record/connection_adapters/postgresql/oid') diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/oid/rails_5_1_point.rb b/activerecord/lib/active_record/connection_adapters/postgresql/oid/rails_5_1_point.rb new file mode 100644 index 0000000000..7427a25ad5 --- /dev/null +++ b/activerecord/lib/active_record/connection_adapters/postgresql/oid/rails_5_1_point.rb @@ -0,0 +1,50 @@ +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 + 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 -- cgit v1.2.3