Skip to content

Instantly share code, notes, and snippets.

@h3h
Last active August 29, 2015 14:04
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 h3h/9ff609cef17b5fdfd682 to your computer and use it in GitHub Desktop.
Save h3h/9ff609cef17b5fdfd682 to your computer and use it in GitHub Desktop.
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