Copied code from rails latest commit