Since this is so complicated it'd be great to see it pushed in to separate methods (or even class/module if necessary). Doing so should make it easier to process what's happening throughout the process.