Pushing business logic to the models

Ademar

Ademar / December 21, 2018

When reading Ruby on Rails code, I find it difficult to understand code where the "business logic" is scattered between controllers and model.

How do your make code more readable? Specifically how do you make Ruby on Rails code more readable?


The solution is based on this discussion:

DHH

https://m.signalvnoise.com/on-writing-software-well/


The idea that I got from the video s to be able to execute the "business logic" using methods from a set of core models.

In one of our project, that involves rentals, we can access down the business logic by pushing the logic down to the Rental model.

Example Scenario:

Renter selects a listing and clicks on "Request to Book" button on ListingsController#show page.

For this workflow we initially create a Rental.

Rental.create(rental_params)

Renter is redirected to PaymentsController#new page, where the renter can input the credit card details to pay for the listing.

Payment.create(payment_params)

On this workflow we record a Payment which contains the necessary details to execute the payment on stripe.

The lender then approves or declines the rental request through ReviewRentalRequestController#update. On this step, the Renter is also charged on stripe and fund is put into an escrow.

@rental.request.approve!

# or

@rental.request.decline!

This approves or declines the request. The admin can then, "Release" the fund.

@rental.stripe.release_escrow!

This accesses the Stripe API and creates a payout.

Notice that the Rental is the model that contains all the business logic of the Rental workflow.