Delegations in Rails

Rabin Poudyal
2 min readMay 17, 2018

--

Delegations allow the request that comes to an object’s attribute to be delegated or referred to another object. Let’s take an example, we have a physical clothing store and we want to building an online store for selling shirts. So we created two models Product and Variations.

In our store we have shirts of different variations like variations in colors, size and more. So we want to keep track of which variation’s products sales more so we can order that product more in next season.

When the user puts the shirt in the shopping cart we want to know the price of shirt. So what is in their shopping cart is not the shirt but it is the variation of shirt. We need to know the price of that variation. It is not generally good idea to have price of each of our variations because blue, red, green all shirts of same variations cost the same. So we want to send the price request to the product. The product class is the one which knows how much the variation of product costs. So we need to ask product class about the cost of variation.

To achieve that we can write a simple ruby code as above.

But delegations is the cleaner way to do the same thing. So now instead of writing a custom method in the variations class we can simply put one line of ruby code to delegate all request for price attribute to product.

So now when you do variation.price, it will delegate to product class for the price.

You can also put more than one attributes in an array

delegate [:price, :sold_by, :discount] , :to => :product

Delegations goes from child to parent. For example like in our previous example from Variation to Product. If it goes from parent to child then it would not know which child to ask for.

If the attribute we are delegating does not exist in the parent, then it can also be the method in the parent.

Delegations are just short way of writing code that are much cleaner and easier to write.

If you love this article and want to learn more tips about rails. Don’t forget to click on the clap button and follow me on medium, twitter .

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Rabin Poudyal
Rabin Poudyal

Written by Rabin Poudyal

Software Engineer, Data Science Practitioner. Say "Hi!" via email: rabinpoudyal1995@gmail.com or visit my website https://rabinpoudyal.com.np

No responses yet

Write a response