Question

In mysql2 gem, we can use this statement to make all query result symbolized

require 'mysql2'
Mysql2::Client.default_query_options.merge!(symbolize_keys: true)
DB = Mysql2::Client.new(host: "localhost", username: "benchmarkdbuser", password: 'benchmarkdbpass')
DB.select_db('hello_world')
res = DB.query "SELECT id, message FROM Fortune"
rows = res.map { |row| row }
# [{id: 1, message: 'bla'}] --> id and message are symbols, not strings

how to do this on pg gem?

require 'pg'
DB = PG::Connection.new('localhost',5432,nil,nil,'hello_world','benchmarkdbuser','benchmarkdbpass')
res = DB.query "SELECT id, message FROM Fortune"
rows = res.map { |row| row }
# [{"id" => 1, "message" => "bla"}] --> id and message are strings, not symbols
Was it helpful?

Solution

If there is no native way:

h_to_sym = ->(row){ row.keys.each_with_object({}) { |k, o|
  o[k.to_sym] = row[k].is_a?(Hash) ? h_to_sym.(row[k]) : row[k] }
}
p res.map.with_object([]) { |row, h| h << h_to_sym.(row) }

This also supports joined models.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top