refactoring from the rails master of deasaster