Last active
December 13, 2015 17:28
-
-
Save tlux/4947825 to your computer and use it in GitHub Desktop.
PostgreSQL HStore Parser & Dumper
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
module HStore | |
class << self | |
def parse(str) | |
hash = Hash[*str.to_s.split(',').map do |item| | |
if item.strip =~ /\A\"(.*)\"[ ]*=>[ ]*(.*)\z/ | |
key = $1.to_sym | |
value = $2 =~ /\"(.*)\"/ ? $1 : nil | |
[key, value] | |
else | |
raise ArgumentError, 'invalid format' | |
end | |
end.flatten] | |
hash = hash.with_indifferent_access if hash.respond_to? :with_indifferent_access | |
hash | |
end | |
def dump(hash) | |
raise ArgumentError, 'invalid format' unless hash.is_a? Hash | |
hash.map do |key, value| | |
value = value.nil? ? "NULL" : "\"#{value}\"" | |
"\"#{key}\"=>#{value}" | |
end.join(',') | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment