Created
February 27, 2012 12:14
-
-
Save afgomez/1923380 to your computer and use it in GitHub Desktop.
Convert a hash into a valid key=value SQL string
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
# gives a valid key=value SQL string for using in "INSERT INTO `table` SET" sentences | |
# >> "INSERT INTO `table_name` SET #{sqlize(Model.find(id).attributes)};" | |
# returns | |
# => "INSERT INTO `table_name` SET `attr1`=value1,`attr2`=value2..." | |
# Handles different datatypes | |
def sqlize hash | |
hash.map do |k,v| | |
v = case v | |
when Time | |
%{"#{v.to_s(:db)}"} | |
when TrueClass | |
1 | |
when FalseClass | |
0 | |
when NilClass | |
"NULL" | |
when String | |
%{"#{v.gsub(/['"\\\x0]/,'\\\\\0')}"} | |
else | |
v | |
end | |
"`#{k}`=#{v}" | |
end.join(',') | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ActiveRecord::Base implementa esto en sanitize_sql_hash_for_assignment:
ActiveRecord::Base.send(:sanitize_sql_hash_for_assignment,{:wadus=> 'wadus', :foo => nil})
=> "
foo
= NULL,wadus
= 'wadus'"