-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Methods and Blocks
-
Section 4: Object-Oriented Ruby
-
Section 5: Metaprogramming
-
Section 6: Working with Data and Files
-
Section 7: Ruby Frameworks Overview
-
Section 8: Ecosystem and Testing
-
Section 9: Practical Projects
-
Section 10: Interview Practice
-
Section 11: Data Structures and Algorithms in Ruby
-
Section 12: More Practice Exercises
-
Section 13: Enumerable and Functional Style
-
Section 14: More OOP Practice
-
Section 15: More Testing
-
Section 16: Enumerable and Comparable Modules In Depth
-
Section 17: Ruby Standard Library: Core Utilities
-
Section 18: Ruby Standard Library: Data and Security
-
Section 19: Ruby Standard Library: CLI and Text
-
Section 20: Ruby Networking
-
Section 21: Ruby on Rails Deep Dive
-
Section 22: Ruby Metaprogramming Deep Dive
-
Section 23: Ruby Design Patterns
-
Section 24: Ruby Concurrency
-
Section 25: Ruby Testing Deep Dive
-
Section 26: Ruby Gems and Packaging
-
Section 27: Ruby Performance
-
Section 28: More Practice Exercises
-
Section 29: More Interview Practice
-
Section 30: Rails API Development
-
Section 31: Rails Authentication and Authorization
-
Section 32: Rails Testing Deep Dive
-
Section 33: Rails Performance
-
Section 34: Rails Deployment
-
Section 35: Sinatra and Lightweight Ruby Web Apps
-
Section 36: More Ruby Language Deep Dive
-
Section 37: Ruby 3.x Modern Features
-
Section 38: More Data Structures in Ruby
-
Section 39: More Practical Projects
-
Section 40: Ruby Ecosystem Tools
-
Section 41: More Practice and Review
-
Section 42: Final Practice and Mastery
-
Section 43: Ruby Interview Deep Dive
-
Section 44: Ruby Background Processing Deep Dive
-
Section 45: Ruby GraphQL
-
Section 46: Ruby Object Model Deep Dive
-
Section 47: Ruby Hanami Framework Overview
-
Section 48: Ruby gRPC and Protocol Buffers
-
Section 49: Ruby Data Processing
-
Section 50: Ruby Search Integration
-
Section 51: Ruby File Upload and Media
-
Section 52: Ruby Email and Notifications
-
Section 53: Ruby Admin Panels
-
Section 54: Ruby Feature Flags and Experimentation
-
Section 55: Ruby Monitoring and Observability
-
Section 56: Ruby Docker and Deployment Deep Dive
-
Section 57: Ruby Security Deep Dive
-
Section 58: More Advanced Metaprogramming
-
Section 59: More Final Projects
172: Practice Exercise: Building a Simple Event Sourcing System in Ruby
Up until now, we've mostly talked about CRUD—creating a record, updating its columns, and saving the current state to a database. But in complex systems, knowing how you got to the current state is often more important than the state itself. That's where Event Sourcing comes in. Instead of storing a row that says balance: 100, we store a list of events: Deposited(50), Deposited(70), Withdrawn(20).
Defining our Event Types
To start, we need a way to represent these events. I prefer using Struct for this in Ruby because events should be immutable data carriers. They shouldn't have logic; they should just describe something that happened in the past.
MoneyDeposited = Struct.new(:amount, :timestamp)
MoneyWithdrawn = Struct.new(:amount, :timestamp)
AccountOpened = Struct.new(:owner, :timestamp)
By separating these into distinct types, we can use pattern matching (which Ruby has become quite good at) to handle them differently when we reconstruct our account state.
Reconstructing State from the Stream
Now we need the "Aggregate"—the object that actually holds the current balance. The trick here is that the BankAccount doesn't have a save method that writes to a row. Instead, it has an apply method that updates the state based on an event.
class BankAccount
attr_reader :balance, :owner
def initialize
@balance = 0
@owner = nil
end
def apply(event)
case event
when AccountOpened
@owner = event.owner
when MoneyDeposited
@balance += event.amount
when MoneyWithdrawn
@balance -= event.amount
end
self
end
def load_from_history(events)
events.each { |event| apply(event) }
self
end
end
Wait, I broke the invariants
I initially wrote the apply method to handle the logic of whether a withdrawal was allowed. I tried putting a raise "Insufficient Funds" inside the MoneyWithdrawn case. That was a mistake.
Here is why: Event Sourcing splits "Command" (the request to do something) from "Event" (the fact that it happened). The apply method is used to replay history. If I put a validation check in apply, then a year from now, if I change the overdraft rules, I might find that I can no longer "load" old accounts because they fail the new validation logic during replay. Replaying events must be deterministic and unconditional. Validations happen before the event is created, not during the replay.
I've fixed the code above to ensure apply simply updates the state. If we wanted to validate a withdrawal, we'd create a separate withdraw(amount) method that checks the balance and then emits a MoneyWithdrawn event.
Gluing it together with a basic Store
To make this useful, we need a way to persist these events. In a production app, you'd use something like EventStoreDB or a Postgres table, but for our exercise, a simple hash will do. I'll create a store that keeps track of streams indexed by an account ID.
class SimpleEventStore
def initialize
@streams = Hash.new { |h, k| h[k] = [] }
end
def append_to_stream(stream_id, event)
@streams[stream_id] << event
end
def get_stream(stream_id)
@streams[stream_id]
end
end
# Let's see it in action
store = SimpleEventStore.new
account_id = "acc_123"
# Simulate activity
store.append_to_stream(account_id, AccountOpened.new("Alice", Time.now))
store.append_to_stream(account_id, MoneyDeposited.new(100, Time.now))
store.append_to_stream(account_id, MoneyWithdrawn.new(30, Time.now))
# Reconstruct the account
history = store.get_stream(account_id)
account = BankAccount.new.load_from_history(history)
puts "Account Owner: #{account.owner}" # Alice
puts "Current Balance: #{account.balance}" # 70
The beauty of this is the audit trail. If Alice asks why her balance is 70, we don't have to guess; we have the exact sequence of events that led to that number.
📋 Practical Task
Exercise: Building a Warehouse Inventory Event Stream
You need to build a simplified inventory tracking system using the Event Sourcing pattern we just covered. Instead of a bank account, you are tracking the quantity of items in a warehouse.
Requirements:
- Define three event types using
Struct:ItemReceived(adds stock),ItemShipped(removes stock), andInventoryAdjusted(sets stock to a specific number, used for manual audits). - Create an
InventoryItemclass with anapplymethod that handles these three events to maintain a@quantitystate. - Implement a
load_from_historymethod to rebuild the state from an array of events. - Create a small script that:
- Appends a sequence of these events to a list (representing a stream).
- Reconstructs the
InventoryItemfrom that stream. - Prints the final quantity to the console.
Hint: Remember to keep your apply method purely focused on state updates—do not put validation logic (like preventing negative stock) inside the replay loop!
There are no comments for now.