Refactor Rails and add debug information

@redlibrarian can you check my work and merge?