Design Patterns in Ruby On Rails - Run With Code

Latest

Learn Ruby On Rails , Linux and IoT(Internet Of Things).

Amazon

Sunday 19 April 2020

Design Patterns in Ruby On Rails

Rails Design Patterns 

The main principle of software development is to keep the code DRY (Don’t Repeat Yourself) to reduce the reduction in the code. So, Ruby On Rails follows some design patterns to achieve the DRY principle. Though we can use models, helpers, and concerns to make the code dry, if the code complexity is higher or we are using external API, in that case, we use rails Design Patterns.
Here is the ruby on rails design patterns:
Let’s Discuss the all above-mentioned ruby design patterns one by one with examples.

(1) Service Objects

  • What is a
  • A Service Object is PORO – Plain Old Ruby Object, which is meant to encapsulate business logic and complex calculations into manageable classes and methods.
  • When to use service objects?
  • 1. When we need to perform complex calculations or business logic, for, e.g. if we need to calculate employee’s salaries based on their attendance.
    2. When we need to implement any other API, for, eg. we need to implement payment gateway such as Stripe.
    3. When we want to import CSV that contains the bulk of data.
    4. When we need to clear garbage/unused/old data from the database in an efficient manner that it won’t affect the existing data.
In this example, we perform stripe integration with the help of Service Object. Here the stripe service will create stripe customers based on their email address and token.
Have a look at PaymentsController; here, you can see that the controller is too skinny. Payment service has solved the problem of too much code inside the controller and made the controller skinny and readable.
PaymentsController
Now create payment_service.rb inside your_project/app/services folder.

Thanks For reading For more information
For more information

No comments:

Post a Comment

Please do not enter any spam link in the comment box.