Skip to content

Instantly share code, notes, and snippets.

@Osseta
Created January 17, 2012 03:52
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 Osseta/1624535 to your computer and use it in GitHub Desktop.
Save Osseta/1624535 to your computer and use it in GitHub Desktop.
Monkey Patch Rails PG Adapter to support calculated values
require 'active_record/connection_adapters/abstract_adapter'
require 'active_support/core_ext/kernel/requires'
require 'active_support/core_ext/object/blank'
module ActiveRecord
module ConnectionAdapters
class PostgreSQLAdapter < AbstractAdapter
# create a 2D array representing the result set
def result_as_array(res) #:nodoc:
# check if we have any binary column and if they need escaping
unescape_col = []
res.nfields.times do |j|
unescape_col << res.ftype(j)
end
ary = []
res.ntuples.times do |i|
ary << []
res.nfields.times do |j|
data = res.getvalue(i,j)
#
# FIND THE TYPES WITH SELECT typname, oid FROM pg_type
#
#
case unescape_col[j]
# if this is a boolean, convert data
when 16
data = (data.nil? || data == '') ? nil : (data == 't')
# if this is an integer, convert the data
when 23
data = (data.nil? || data == '') ? nil : data.to_i
# if this is a timestamp, convert the data
when 1114
data = (data.nil? || data == '') ? nil : DateTime.parse(data + " +00:00").in_time_zone
# unescape string passed BYTEA field (OID == 17)
when BYTEA_COLUMN_TYPE_OID
data = unescape_bytea(data) if String === data
# If this is a money type column and there are any currency symbols,
# then strip them off. Indeed it would be prettier to do this in
# PostgreSQLColumn.string_to_decimal but would break form input
# fields that call value_before_type_cast.
when MONEY_COLUMN_TYPE_OID
# Because money output is formatted according to the locale, there are two
# cases to consider (note the decimal separators):
# (1) $12,345,678.12
# (2) $12.345.678,12
case data
when /^-?\D+[\d,]+\.\d{2}$/ # (1)
data.gsub!(/[^-\d\.]/, '')
when /^-?\D+[\d\.]+,\d{2}$/ # (2)
data.gsub!(/[^-\d,]/, '').sub!(/,/, '.')
end
end
ary[i] << data
end
end
return ary
end
end
end
end
@luccasmaso
Copy link

Nice! I will use it here too. Did you make some update along these years or find other solution?
Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment