Skip to content

Instantly share code, notes, and snippets.

@daniel-rikowski
Last active August 29, 2015 14:22
Show Gist options
  • Save daniel-rikowski/8579c2c591ec01814036 to your computer and use it in GitHub Desktop.
Save daniel-rikowski/8579c2c591ec01814036 to your computer and use it in GitHub Desktop.
Array of points error
# Activate the gem you are reporting the issue against.
gem 'activerecord', '4.2.1'
require 'active_record'
require 'minitest/autorun'
require 'logger'
# Ensure backward compatibility with Minitest 4
Minitest::Test = MiniTest::Unit::TestCase unless defined?(Minitest::Test)
# This connection will do for database-independent bug reports.
ActiveRecord::Base.establish_connection(adapter: 'postgresql', database: 'TODO',
username: 'TODO', password: 'TODO')
ActiveRecord::Base.logger = Logger.new(STDOUT)
ActiveRecord::Schema.define do
drop_table :shapes rescue nil
create_table :shapes do |t|
t.column :centroid, :point
t.column :polygon, :point, array: true
end
end
class Shape < ActiveRecord::Base
end
class ArrayOfPointsTest < Minitest::Test
def test_point # Succeeds
Shape.create!(centroid: [0.4, 0.7])
end
def test_array_of_points # Fails
Shape.create!(polygon: [[0.1, 0.2],
[0.3, 0.4],
[0.5, 0.6],
[0.7, 0.8],
[0.1, 0.2]])
end
end
ActiveRecord::ConnectionAdapters::PostgreSQL::OID::Array.class_eval do
def cast_value_for_database(value)
if value.is_a?(::Array)
if subtype.type == :point
casted_values = value.map do |item|
if item.is_a?(::Array) && !item.first.is_a?(Array)
quote_and_escape(subtype.type_cast_for_database(item))
else
cast_value_for_database(item)
end
end
"{#{casted_values.join(delimiter)}}"
else
casted_values = value.map { |item| cast_value_for_database(item) }
"{#{casted_values.join(delimiter)}}"
end
else
quote_and_escape(subtype.type_cast_for_database(value))
end
end
end
ActiveRecord::ConnectionAdapters::PostgreSQL::OID::Array.class_eval do
def type_cast_array(value, method)
if value.is_a?(::Array)
if @subtype.type == :point
value.map do |item|
if item.is_a?(::Array) && !item.first.is_a?(Array)
@subtype.public_send(method, item)
else
type_cast_array(item, method)
end
end
else
value.map { |item| type_cast_array(item, method) }
end
else
@subtype.public_send(method, value)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment