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
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) 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.