Skip to content

Instantly share code, notes, and snippets.

@h3h h3h/README.md
Last active Aug 29, 2015

Embed
What would you like to do?
Adding to/from GeoJSON Conversions to Sequel Queries

SQL for INSERT:

INSERT INTO geographies (type, name, geometry)
VALUES (
  'Location',
  'Vintage Heart Coffee',
  ST_GeomFromGeoJSON('{"type": "Point", "coordinates": [30.2642, -97.7277]}')
);
-- INSERT 0 1

SQL for SELECT:

SELECT name, ST_AsGeoJSON(geometry) as geo from geographies;
--          name         |                        geo                        
-- ----------------------+---------------------------------------------------
--  Vintage Heart Coffee | {"type":"Point","coordinates":[30.2642,-97.7277]}
-- (1 row)
require 'delegate'
module Sequel
module GeoJSON
class GeoJSONGeometry < DelegateClass(Hash)
def sql_literal_append(ds, sql)
ds.literal_append(sql, Sequel.function(:ST_GeomFromGeoJSON, self))
end
end
module DatabaseMethods
def self.extended(db)
db.instance_eval do
add_named_conversion_procs(conversion_procs, :geometry => PG_NAMED_TYPES[:geometry])
@schema_type_classes[:geometry] = [GeoJSONGeometry]
end
end
end
PG_NAMED_TYPES = {} unless defined?(PG_NAMED_TYPES)
# Associate the named types by default.
PG_NAMED_TYPES[:geometry] = JSON.method(:parse)
end
Database.register_extension(:geojson, GeoJSON::DatabaseMethods)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.