Sha256: 504f0a4bb33b11b196138a7be651495ea1a41aa37df5cca3b2321fd3ea4ad992

Contents?: true

Size: 1.58 KB

Versions: 1

Compression:

Stored size: 1.58 KB

Contents

# frozen_string_literal: true

module ActiveRecord
  module ConnectionAdapters
    module CipherStashPG
      Point = Struct.new(:x, :y)
      module OID # :nodoc:
        class Point < Type::Value # :nodoc:
          include ActiveModel::Type::Helpers::Mutable

          def type
            :point
          end

          def cast(value)
            case value
            when ::String
              return if value.blank?

              if value.start_with?("(") && value.end_with?(")")
                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 quacks_like_a_point(value)
              "(#{number_for_point(value.x)},#{number_for_point(value.y)})"
            elsif ::Array === value
              serialize(build_point(*value))
            else
              super
            end
          end

          def type_cast_for_schema(value)
            if quacks_like_a_point?(value)
              [value.x, value.y]
            else
              super
            end
          end

          private
            def number_for_point(number)
              number.to_s.delete_suffix(".0")
            end

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

            def quacks_like_a_point?(value)
              value.respond_to(:x) && value.respond_to(:y)
            end
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
activerecord-cipherstash-pg-adapter-0.7.6 lib/active_record/connection_adapters/7.0/cipherstash_pg/oid/point.rb