Refactor and clean up ready for rails 4 upgrade