Refactoring Ruby on Rails

Ruby on Rails / Refactoring – parameter object pattern

Ruby on Rails / Refactoring – parameter object pattern February 1, 20183 Comments

Sometimes is hard no to pass many parameters to a single method and this is the moment when parameter object comes in. The parameter object is a primitive Ruby object where parameters are attributes so you can pass one argument which is an object instance instead of multiple parameters. Let’s jump to a sample class to better demonstrate it:

class Notificator
  def push_update(title, content, category)
    some_api_class.push(title: title, content: content, category: category)
  end
end

We have some sample class responsible for pushing an update to the API. As we can see our parameters are related to the API message. Let’s create a simple class which will be our parameter object in this case:

class ApiMessage
  attr_reader :title, :content, :category
  
  def initialize(title:, content:, category:)
    @title = title
    @content = content
    @category = category
  end
end

Now we can update our Notificator class to require only one method argument:


class Notificator
  def push_update(api_message)
    some_api_class.push(title: api_message.title, content: api_message.content, category: api_message.category)
  end
end

Our code is more readable now and it will be easier to test it. It’s important to treat parameter object as a very simple object otherwise we would miss the idea behind this refactoring pattern and we would end up with a normal class including some extra functionality and a lot of code.

Download free RSpec & TDD ebook

Do you want to earn more or jump to the next level in your company? Do you know that testing skills are one of the most desired skills? There is only first step: start testing and do it right. My ebook can help you. Subscribe to the newsletter to get a free copy of the book.

3 comments

  1. Hi, thanks for the article.

    Do you think this is really worth it in this case?

    The code becomes a lot more “noisy” after your refactoring with “api_message” repeated 3 times. How about using a hash instead?

    1. I think we can also use key arguments, it will be more readable than a hash. However, this is a very simple case so it may be not worth to do this but I wanted to just present the idea behind this pattern

Leave a Reply

Your email address will not be published. Required fields are marked *