Skip to content

Instantly share code, notes, and snippets.

@radcliff
Last active August 29, 2015 14:19
Show Gist options
  • Save radcliff/af05593ca19d38b8678b to your computer and use it in GitHub Desktop.
Save radcliff/af05593ca19d38b8678b to your computer and use it in GitHub Desktop.
Transforming PostgreSQL arrays
# monkey patch String class
# source: http://drawingablank.me/blog/ruby-boolean-typecasting.html
class String
def to_bool
return true if self == true || self =~ (/^(true|t|yes|y|1)$/i)
return false if self == false || self.empty? || self =~ (/^(false|f|no|n|0)$/i)
raise ArgumentError.new("invalid value for Boolean: \"#{self}\"")
end
end
# Postgres returns an array as a string like "{true,false,true,true,false}"
# type: 'boolean' or 'integer'
def transform_pg_array(string, type)
return [] if string.nil?
array = string.split(',')
if type == 'boolean'
array.map! do |element|
element = /true|false/.match(element).to_s
element.to_bool
end
elsif type == 'integer'
array.map! do |element|
element = /\d+/.match(element).to_s
element.to_i
end
else
raise ArgumentError, 'please specify a type to cast into: (boolean|integer)'
end
return array
end
@radcliff
Copy link
Author

Usage

transform_pg_array("{true,false,true,true,false}", 'boolean')
# => [true, false, true, true, false]

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