Refactor Rails code