Use attr_extras Gem to Refactor a Ruby Class


This guide examines how to streamline a class definition in Ruby by using the attr_extras Ruby gem. This gem allows you to remove unnecessary boilerplate code when you define attributes in Ruby.


Refactor a Ruby class so that it uses the attr_extras gem.

Exercise File

Code File

Exercise Description

Clean up how Ruby defines its list of attributes by leveraging the attr_extras gem. This will allow you to remove unnecessary boilerplate code when listing attributes.

Class to Refactor

class PurchaseOrder
  attr_accessor :client, :total

  def initialize(client, total)
    @client = client
    @total = total

  def generate_order
    "#{client}: #{total}"

po ='Google', 500)
po.client # => 'Google'
po.generate_order # => 'Google: 500'

Research the attr_extras gem to see how you can streamline this class and remove the initialize method.

Real World Usage

Ruby is an intuitive programming language. It allows you to skip quite a bit of boilerplate code. For example, in Ruby you won’t have to write class setters and getters manually. However there are still a few processes that you will find yourself repeating on a regular basis. The attr_extras gem is a great tool to help you streamline how you define attributes in a class.


Can be found on the solutions branch on github.


Please enter your comment!
Please enter your name here