January 4 - Perform Monkey Patching in Ruby on Isolated Classes
This coding exercise will teach you how to use Refinements in Ruby in order to add custom functionality to specific classes.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
  • Complete the Exercise
Video locked
This video is viewable to users with a Bottega Bootcamp license

Summary

Implement Refinements in Ruby so that a method can be added to a String class, but only for specific classes.

Exercise Description

Given the following class definition:

class ContentController
  def initialize(word)
    @word = word
  end

  def hidden_content
    @word.commentize
  end
end

Implement a Refinement to the String class that adds the commentize method, but only for specific classes (instead the global String class like typical monkey patching)

Sample Output

cc = ContentController.new("My String")
cc.hidden_content # "# My String"

Real World Usage

Monkey patching can cause a number of negative side effects in a program, by leveraging refinements you will be able to be specific about which classes can access the class changes.

Test Cases

Code File