ruby
35 lines · 9 steps
Delegation in Ruby with Forwardable
How Forwardable and Enumerable let a ShoppingCart borrow behavior from the objects it wraps instead of reimplementing it.
Explained by
highlit
1require "forwardable"
2
3class ShoppingCart
4 extend Forwardable
5
6 def_delegators :@items, :each, :size, :empty?, :map, :sum
7 def_delegator :@customer, :name, :customer_name
8 def_delegator :@customer, :email, :customer_email
9
10 include Enumerable
11
12 def initialize(customer)
13 @customer = customer
14 @items = []
15 end
16
17 def add(product, quantity: 1)
18 @items << LineItem.new(product, quantity)
19 self
20 end
21
22 def total
23 sum(&:subtotal)
24 end
25
26 def to_s
27 "Cart for #{customer_name} (#{size} items, $#{format('%.2f', total)})"
28 end
29
30 LineItem = Struct.new(:product, :quantity) do
31 def subtotal
32 product.price * quantity
33 end
34 end
35end
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Forwardable lets a class expose methods of its collaborators without hand-writing wrapper methods.
- 2Delegating iteration methods and mixing in Enumerable gives you dozens of collection methods for free.
- 3Composing objects and forwarding messages keeps a class focused on its own responsibilities.
Related explainers
ruby
class Order class InvalidTransition < StandardError; end TRANSITIONS = {
A state machine for order transitions in Ruby
state-machine
data-driven
error-handling
Intermediate
8 steps
ruby
class CreateOrderItems < ActiveRecord::Migration[7.1] def change create_table :order_items do |t| t.references :order, null: false, foreign_key: { on_delete: :cascade }
Enforcing order-item integrity in Rails
migrations
foreign-keys
validations
Intermediate
7 steps
ruby
class Registration < ApplicationRecord belongs_to :event validates :email, presence: true, format: { with: URI::MailTo::EMAIL_REGEXP }
Validating registrations in Rails
validations
i18n
error-handling
Intermediate
8 steps
ruby
class ApacheLogParser LINE_PATTERN = /\A(?<ip>\S+)\s\S+\s\S+\s\[(?<time>[^\]]+)\]\s"(?<method>[A-Z]+)\s(?<path>\S+)\s(?<protocol>[^"]+)"\s(?<status>\d{3})\s(?<bytes>\d+|-)/ TIME_FORMAT = "%d/%b/%Y:%H:%M:%S %z"
Parsing Apache logs with named captures
regex
named-captures
parsing
Intermediate
6 steps
ruby
require "csv" def parse_transaction_row(line) fields = CSV.parse_line(line, headers: false, skip_blanks: true)
Parsing one CSV transaction row in Ruby
parsing
type-coercion
error-handling
Intermediate
6 steps
ruby
class NewCommentNotifier < ApplicationNotifier deliver_by :database deliver_by :email do |config|
Multi-channel notifications with Noticed in Rails
notifications
delivery-methods
fan-out
Intermediate
6 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/delegation-in-ruby-with-forwardable-explained-ruby-6515/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.