Created
October 26, 2016 14:12
-
-
Save jugyo/f22fb74496c49cf41efc1b0f0baf4b10 to your computer and use it in GitHub Desktop.
A patch for spatial data support for rails's mysql2 adapter, only support `point` geometry data
This file contains hidden or 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 'geo_ruby/ewk' | |
# NOTE: Set SRID 0 as same as mysql's default | |
GeoRuby::SimpleFeatures::DEFAULT_SRID = 0 | |
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 | |
module ConnectionAdapters | |
class Mysql2Adapter | |
def quote_with_spatial(value_, column_ = nil) | |
if value_.is_a?(GeoRuby::SimpleFeatures::Point) | |
"GeomFromWKB(0x#{value_.as_hex_wkb},#{value_.srid})" | |
elsif column_ && column_.type == :spatial && value_.is_a?(String) | |
# NOTE: For fixture | |
value_ | |
else | |
quote_without_spatial(value_, column_) | |
end | |
end | |
alias_method_chain :quote, :spatial | |
def initialize_type_map_with_spatial(m) | |
initialize_type_map_without_spatial(m) | |
# NOTE: Only support `point` geometry data | |
m.register_type(%r(point)i) { |sql_type| ActiveRecord::Type::Spatial.new } | |
end | |
alias_method_chain :initialize_type_map, :spatial | |
end | |
end | |
end | |
ActiveRecord::Base.connection.clear_cache! # NOTE: To `reload_type_map` that reload column types |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment