March 8 - 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.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
  • Complete the Exercise
Video locked
This video is viewable to users with a Bottega Bootcamp license

Summary

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
  end

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

po = PurchaseOrder.new('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.

Solution

Can be found on the solutions branch on github.