Ruby Coding Exercise: How to Use Ruby Refinements to Adds Methods to Customized Classes

0
871

This coding exercise will teach you how to use Refinements in Ruby in order to add custom functionality to specific classes.

Summary

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

Exercise File

Code File

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 Outpout

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.

Solution

Can be found on the solutions branch on github.

LEAVE A REPLY

Please enter your comment!
Please enter your name here