extracted piece of code into a method

Can someone merge this to master and to 4-0-stable. I need this fix in 4-0-stable to send PR for https://github.com/rails/rails/issues/10421 .

In this PR existing code has been moved to another method . No business logic is changed.