Skip to content

Instantly share code, notes, and snippets.

@marten
Created June 21, 2011 08:15
Show Gist options
  • Save marten/1037446 to your computer and use it in GitHub Desktop.
Save marten/1037446 to your computer and use it in GitHub Desktop.
class MergeAdhd < ActiveRecord::Migration
def self.up
adhd1 = RoquaQuestionnaire.find_by_key "adhd"
adhd1_bulk = RoquaQuestionnaire.find_by_key "adhd_bulk"
adhd2 = RoquaQuestionnaire.find_by_key "adhd2"
adhd2_bulk = RoquaQuestionnaire.find_by_key "adhd2_bulk"
[adhd1, adhd1_bulk, adhd2, adhd2_bulk].each do |q|
# Prefix all values.keys with questionnaire.key
q.answers.each do |answer|
result = answer.values.map do |key, value|
["#{q.key}_#{key}", value]
end
answer.values = Hash[*result.flatten]
answer.save
end
# Update q.vars to reflect the new prefix
q.vars = q.variables.map{|i| "#{q.key}_#{i}"}
# Update q.to_bulk to reflect the new prefix
q.to_bulk_will_change!
result = q.to_bulk.map{|key, value| ["#{q.key}_#{key}", "#{q.key}_#{value}"] }
q.to_bulk = Hash[*result.flatten]
q.save
end
# Find pairs
by_patient = {}
[adhd1, adhd1_bulk, adhd2, adhd2_bulk].each do |q|
q.answers.each do |answer|
next unless answer.active
by_patient[answer.subject_id] ||= {}
by_patient[answer.subject_id][answer.meas_instance_id] ||= []
by_patient[answer.subject_id][answer.meas_instance_id] << answer
end
end
# Sanity check
by_patient.each do |subject_id, meas_instances|
meas_instances.each do |meas_instance_id, answers|
raise "Too many answers for #{subject_id} -> #{meas_instance_id}" if answers.size > 2
end
end
# Merge pairs
by_patient.each do |subject_id, meas_instances|
meas_instances.each do |meas_instance_id, answers|
RoquaAnswer.transaction do
one = answers.find{|i| [adhd1.id, adhd1_bulk.id].include?(i.questionnaire_id) }
two = answers.find{|i| [adhd2.id, adhd2_bulk.id].include?(i.questionnaire_id) }
one.values = one.values.merge(two.values)
one.save!
two.active = false
two.save!
end
end
end
# Disable the now unused adhd2 questionnaire
adhd2.active = false; adhd2.save
adhd2_bulk.active = false; adhd2_bulk.save
# Convert to QubyQuestionnaire
adhd1.convert_to_quby_questionnaire("adhd")
end
def self.down
# raise IrreversibleMigration
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment