From bug rails 4

This fixes issue #256. Includes tests.

Tried to learn how you do things as fast as I could, but I suspect this could be more robust.

Thoughts?