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)

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

Want to receive useful tips, information about new Ruby gems and articles on a daily basis? Make sure you follow me and say hello!

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)

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.

Want to become a better Rails developer?
Download for free the Introduction Rails patterns book and dive into the world of refactoring and easy-testable Ruby code today.
Join over 1,000 developers already subscribed to my newsletter and download the book. You can unsubscribe anytime:

Subscribe and get the book!