Skip to content

Instantly share code, notes, and snippets.

@chrisbloom7
Last active June 5, 2025 20:00
Show Gist options
  • Save chrisbloom7/4e88549fa445af7326440b2adc852f36 to your computer and use it in GitHub Desktop.
Save chrisbloom7/4e88549fa445af7326440b2adc852f36 to your computer and use it in GitHub Desktop.
A simple Ruby refactoring exercise to improve a conditional-heavy method. Includes inline regression tests for both RSpec and Minitest.

Refactoring Excercise

Here’s a messy, unoptimized Ruby method. Let’s clean it up.

  • How can we make this more extensible?
  • How should it handle invalid inputs (negative prices, nil codes)
  • How could we extract this logic into a separate class/module
require "bundler/inline"
gemfile do
gem "rspec"
gem "minitest"
end
def messy_calculate_discount(price, discount_code)
if discount_code == 'SUMMER10'
discount = price * 0.1
elsif discount_code == 'WELCOME5'
discount = price * 0.05
elsif discount_code == 'SUPER20'
discount = price * 0.2
else
discount = 0
end
final_price = price - discount
if final_price < 0
final_price = 0
end
return final_price
end
# ------------------------------------------
# RSpec Tests (if using rspec)
# Run: rspec discount_calculator.rb
# ------------------------------------------
if defined?(RSpec)
RSpec.describe "Discount Calculator" do
it 'applies SUMMER10 correctly' do
expect(messy_calculate_discount(100, 'SUMMER10')).to eq(90)
end
it 'applies WELCOME5 correctly' do
expect(messy_calculate_discount(100, 'WELCOME5')).to eq(95)
end
it 'applies SUPER20 correctly' do
expect(messy_calculate_discount(100, 'SUPER20')).to eq(80)
end
it 'returns original price if code is unknown' do
expect(messy_calculate_discount(100, 'UNKNOWN')).to eq(100)
end
it 'caps final price at 0' do
expect(messy_calculate_discount(100, 'SUPER20')).to be >= 0
expect(messy_calculate_discount(-100, 'SUPER20')).to eq(0)
end
end
end
# ------------------------------------------
# Minitest Tests (if using minitest)
# Run: ruby discount_calculator.rb
# ------------------------------------------
if __FILE__ == $0
require 'minitest/autorun'
class DiscountCalculatorTest < Minitest::Test
def test_summer10
assert_equal 90, messy_calculate_discount(100, 'SUMMER10')
end
def test_welcome5
assert_equal 95, messy_calculate_discount(100, 'WELCOME5')
end
def test_super20
assert_equal 80, messy_calculate_discount(100, 'SUPER20')
end
def test_unknown_code
assert_equal 100, messy_calculate_discount(100, 'INVALID')
end
def test_negative_price_returns_zero
assert_equal 0, messy_calculate_discount(-100, 'SUMMER10')
end
def test_nil_code
assert_equal 100, messy_calculate_discount(100, nil)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment