Last active
August 29, 2015 14:19
-
-
Save radcliff/af05593ca19d38b8678b to your computer and use it in GitHub Desktop.
Transforming PostgreSQL arrays
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage