Skip to Content
Course content

97: The Strategy Pattern in Ruby

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Imagine you're building a travel app. The user wants to get to the airport, but they have options: they could take an Uber, a city bus, or a train. Regardless of the choice, the end goal is the same—they arrive at the terminal. However, the way they get there (the cost, the time, the process) is completely different for each method.

In programming, we often fall into the trap of handling these options with a giant case statement or a string of if/else blocks. It looks something like this: if transport == 'uber' then ... elsif transport == 'bus' then .... That works for two options, but once you add shuttles, bikes, and walking, your method becomes a bloated monster that's a nightmare to test.

The Strategy Pattern is how we fix that. Instead of one method trying to know every possible way to do something, we move each "way" into its own object. The main class doesn't care how the work is done; it just knows that whatever object it's holding has a method it can call to get the result.

Escaping the Giant Case Statement

Let's look at a real scenario: a shipping calculator for an e-commerce store. You start with FedEx, and then you add UPS. Then DHL. Then a local courier. If you keep adding these to a single ShippingCalculator class, it'll eventually collapse under its own weight.

Instead, we define a "Strategy" for each carrier. In Ruby, we don't need formal interfaces because we have duck typing. As long as every strategy object responds to the same method—let's call it calculate—the main calculator doesn't need to know which carrier it's actually using.

class FedExStrategy
  def calculate(weight)
    weight * 1.5 + 10
  end
end

class UPSStrategy
  def calculate(weight)
    weight * 1.2 + 15
  end
end

class LocalCourierStrategy
  def calculate(weight)
    weight * 2.0 # Flat rate per kg, no base fee
  end
end

Connecting the Strategy to the Context

Now we need a "Context" class. This is the object the rest of your app interacts with. It doesn't contain the math; it just holds a reference to one of the strategies we wrote above. I like to pass the strategy in through the initializer, which makes it incredibly easy to swap out during testing.

class ShippingCalculator
  attr_accessor :strategy

  def initialize(strategy)
    @strategy = strategy
  end

  def total_cost(weight)
    # The calculator doesn't care which strategy is active.
    # It just trusts that @strategy responds to :calculate.
    @strategy.calculate(weight)
  end
end

Here is where the magic happens. You can change the behavior of your calculator at runtime without changing a single line of code inside the ShippingCalculator class:

# Start with FedEx
calc = ShippingCalculator.new(FedExStrategy.new)
puts calc.total_cost(10) # 25.0

# User changes their mind to UPS
calc.strategy = UPSStrategy.new
puts calc.total_cost(10) # 27.0

Why This Actually Matters in Production

You might be thinking, "Isn't this just more classes for the sake of more classes?" I used to think that too. But consider this: when you need to add a new carrier (like DHL), you don't have to touch the ShippingCalculator class at all. You just create a DHLStrategy class and pass it in.

This follows the Open/Closed Principle: your code is open for extension (adding new strategies) but closed for modification (you aren't risking breaking existing logic by editing a 500-line case statement). It turns a risky modification into a safe addition.




📋 Practical Task

Build a Pluggable Payment Processor

You are building a checkout system that needs to support multiple payment gateways. Currently, the system only supports Credit Card payments, but you need to make it flexible enough to add PayPal and Bitcoin without modifying the main checkout logic.

Your Task:

  • Create a PaymentProcessor class (the Context) that accepts a strategy object in its initializer and has a method process_payment(amount).
  • Create three strategy classes: CreditCardPayment, PayPalPayment, and BitcoinPayment.
  • Each strategy should implement a pay(amount) method that prints a specific message (e.g., "Processing $100 via Credit Card...").
  • Demonstrate the Strategy Pattern by instantiating the PaymentProcessor with one strategy, processing a payment, and then swapping the strategy to a different gateway to process another payment.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.