Forum: Ruby on Rails PostGIS 2.1 rasters available to Rails code: breadcrumbs

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
D66942312b1a360a3e172e8cde27a3ed?d=identicon&s=25 lupus (Guest)
on 2013-10-08 21:17
(Received via mailing list)
Just wanted to post this in case someone else was faced with the same
problem. It's database-specific code, worse, it's specific to a
particular *
version* of a particular *extension* to a particular database, wires in
SQL, and uses eval on a string of data from the database!

So, you know, I'm getting coal in my stocking from DHH this year. I can
deal. (After the whole Jolt Award thing years back, though, he totally
me, I wanted to keep that thing so bad...)

Anyway, problem is this: I wanted to do some calculations on some
geospatial raster data, which are to be stored in a GIS-enabled
I'd chosen PostGIS long ago for various reasons. But even the fabulous
gem doesn't know from rasters, or at least not yet AFAIK. So there's no
to get pixels out of the raster except one-by-one with an ST_Value
for a 297x582 array, a nonstarter.

Enter PostGIS 2.1 and its lovely lovely ST_DumpValues and ST_SetValues
functions. By using the connection's select_value method, we can return
arbitrary SQL result as a string, in this case a 2D array coded with the
PostgreSQL convention of { and } where Ruby uses [ and ].

Likewise, connection.update can take an SQL string, and we can wad a 2D
array of values into it with a simple to_s.

So here's the hack:

# Get and set raster band values out of PostGIS 2.1 rasters as Ruby
# This example assumes that the raster column is 'rast' and that the
# key for the table is 'rid'. Also, NULL pixels will probably tank the
# Fixing those is left as an exercise :-)

class PostGisRaster < ActiveRecord::Base

  self.primary_key = 'rid'
  # Grab a band of a raster out of the database and convert it to a 2D
array. Defaults to first band (1)
  def self.to_a(tablename,id,band=1)
    id = id.to_i
    str = connection.select_value("select st_dumpvalues(rast,#{band})
from #{tablename} where #{primary_key}=#{id}")

  # Update a raster band (default: first band) in the database with
values from arr. Note that arr can be any
  # subset of the size of the full raster. Corner is X,Y (or long,lat),
with the upper left corner as [1,1].
  def self.update_raster(tablename,id,arr,band=1,corner=[1,1])
    update_str = <<-END
    select st_setvalues(
      (select rast from #{tablename} where rid=#{id}),
      array#{arr.to_s}::double precision[][]
    update_str = "update #{tablename} set rast=(#{update_str}) where
    puts "update_str: '#{update_str}'"
This topic is locked and can not be replied to.