Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jugyo/52f50d62b61160e58feb502a7d91c452 to your computer and use it in GitHub Desktop.
Save jugyo/52f50d62b61160e58feb502a7d91c452 to your computer and use it in GitHub Desktop.
A patch for Rails 5 to use MySQL spatial index
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