Rails: Implement the Policy object

Tram Ho

This article requires you to have knowledge of object-oriented, Ruby and Ruby on Rails.

What is the policy object design pattern?

Policy objects encapsulate and represent a single business rule.

In our applications we can have different business rules coded mainly as if – else or switch statement. These rules represent concepts in your domain, for example:

  • Is “a customer eligible for a discount?”
  • Will the “email be sent or not?”
  • Does “player get points or not?”

Source: Bài viết này

Let’s get started! (The author uses the Rails API as an example but this article can also be implemented in normal Rails)

1. Make a problem

Suppose we have the following controller:

You put all the policy logic (business rules) in your controller. This is not a good solution. Especially in case you have to deal with a lot of complex logic (controller should only use it for navigation, avoid dealing with a lot of complex logic).

But, we can ignore the class GenerateDiscountVoucherCode. We just need to know that this class is responsible for generating discount voucher codes.

2. Move the Policy logic into the model

Well, we can move the policy logic into the model. So it turns like this:



But this is still not the optimal solution. Adding a policy object logic, although it helps to optimize the controller, but inflates the model. Now let’s implement the policy object design pattern!

3. Create a separate layer

Now, we will create a separate class containing the following policy logic:

Thus, the controller and model will look like this:



4. Summary

Compared to our original controller, this is “just” putting the policy logic in a separate class. That’s true, since our main purpose is to move the policy logic out of the controller and model.

Policy objects encapsulate and represent a single business rule.

You will find this design pattern useful in cases where you have complex policy logic. The example that the author gives is a simple policy logic.


The above article is translated from the source Rails: Policy Objects Implementation

Thank you for reading, have a good day

Share the news now