Skip to content

Instantly share code, notes, and snippets.

@tlux
Last active December 13, 2015 17:28
Show Gist options
  • Save tlux/4947825 to your computer and use it in GitHub Desktop.
Save tlux/4947825 to your computer and use it in GitHub Desktop.
PostgreSQL HStore Parser & Dumper
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