[Ruby] I tried refactoring ①

1 minute read


・ Ruby 2.5.7
・ Rails

Refactor your portfolio code

First of all, the current situation is as follows. Terrible,,. There are eight action names that write almost the same thing. First, let’s refactor the actions from date1 to date8.
スクリーンショット 2020-08-09 14 27 08
スクリーンショット 2020-08-09 14 27 26
スクリーンショット 2020-08-09 14 27 40

What is the process to be divided in each process? What is the same process? Think from the perspective of

First of all, if the processing contents of the actions from date1 to date8 are roughly classified,
date1 is the process of creating a new record.
date2 to date7 are the process of creating a new record + the process of receiving the column passed from the previous page and saving the record.
date8 is the process of receiving the column passed from the previous page and saving the record + the process of saving another record.
So I thought that date2 to date7 could be put together.

How to put together the same process

In this case, it was the existence of this page column that prevented it even if I wanted to refactor it.
On dates2 ~ 7, only the value of page changed, and the code was the same for the subsequent processing, except that the redirect destination was different.
スクリーンショット 2020-08-09 14 53 04

Increase the value each time the page changes

Instead of writing the value of page by myself, I thought that I should code it so that the value is incremented by +1 each time the page changes.
For that purpose, first create an instance variable with @conto_page = 1 on date1.
スクリーンショット 2020-08-09 15 12 13
Next, the value is received on the view side, and @conto_page is passed to date2 with conto_page: @conto_page with form_with.
スクリーンショット 2020-08-09 15 18 46
Finally, if the received params [: conto_page] .to_i == 8, redirect to go to date8, otherwise conto_page will increase by +1.
スクリーンショット 2020-08-09 15 15 10

Refactoring completed!

I was able to safely erase the actions from date3 to date7.
We were able to reduce the amount of code by about 40%.