Created
December 7, 2017 22:41
-
-
Save jugyo/52f50d62b61160e58feb502a7d91c452 to your computer and use it in GitHub Desktop.
A patch for Rails 5 to use MySQL spatial index
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "active_record/connection_adapters/abstract_mysql_adapter" | |
# NOTE: Set SRID 0 as same as mysql's default | |
silence_warnings do | |
GeoRuby::SimpleFeatures::DEFAULT_SRID = 0 | |
end | |
module ActiveRecord | |
module Type | |
class Spatial < Value | |
def type | |
:spatial | |
end | |
private | |
def cast_value(value) | |
return value unless value.is_a?(::String) | |
GeoRuby::SimpleFeatures::Geometry.from_ewkb(value[4..-1]) rescue value | |
end | |
end | |
end | |
end | |
module AbstractMysqlAdapterPatch | |
def initialize_type_map(m) | |
super | |
# NOTE: Only support `point` geometry data | |
m.register_type %r(point)i, ActiveRecord::Type::Spatial.new | |
end | |
def quote(value) | |
if value.is_a?(GeoRuby::SimpleFeatures::Point) | |
"GeomFromWKB(0x#{value.as_hex_wkb},#{value.srid})" | |
else | |
super | |
end | |
end | |
end | |
ActiveRecord::ConnectionAdapters::AbstractMysqlAdapter.prepend AbstractMysqlAdapterPatch |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment