Skip to content

Instantly share code, notes, and snippets.

@dstarh
Last active August 29, 2015 14:23
Show Gist options
  • Save dstarh/aea1a470c29f92ba8511 to your computer and use it in GitHub Desktop.
Save dstarh/aea1a470c29f92ba8511 to your computer and use it in GitHub Desktop.
def diff_table(model_class, sql_file)
inserter = Proc.new do |model_class, other_record|
tribs = other_record.attributes
sql = <<-SQL
--
insert into "#{other_record.class.table_name}"
(#{tribs.collect{|key,value|"\"#{key}\""}.join(",")})
values
(#{tribs.collect{|key,value|"?"}.join(",")})
;
SQL
raw_values = tribs.collect{|key,value|value}
sanitized_sql = ActiveRecord::Base.send(:sanitize_sql_array, [sql, *raw_values])
sql_file.puts sanitized_sql
end
updater = Proc.new do |other_record, our_record|
diff_tribs = other_record.attributes.reject do |key, value|
value == our_record[key]
end
sql = <<-SQL
--
update "#{other_record.class.table_name}"
set #{diff_tribs.keys.collect{|k|"\"#{k}\" = ?"}.join(",")}
where "#{our_record.class.primary_key}" = ?
;
SQL
sanitized_sql = ActiveRecord::Base.send(:sanitize_sql_array, [sql, *diff_tribs.values, our_record.id])
sql_file.puts sanitized_sql
end
deleter = Proc.new do |our_record|
sql = <<-SQL
--
delete from "#{our_record.class.table_name}"
where "#{our_record.class.primary_key}" = ?
;
SQL
sanitized_sql = ActiveRecord::Base.send(:sanitize_sql_array, [sql, our_record.id])
sql_file.puts sanitized_sql
end
process_table model_class, inserter, updater, deleter
end
#works, writes about 10 lines to the file
File.open("sql_file.sql", "w") do |sql_file|
diff_table NutrientInfo, sql_file
end
#doesn't work
string_io = StringIO.new
diff_table NutrientInfo, string_io
puts string_io.string #=> ""
puts string_io.string.length #=> 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment