ruby
40 lines · 7 steps
Building an EventEmitter in Ruby
A pub/sub class that registers blocks per event and fires them on emit, including one-shot listeners.
Explained by
highlit
1class EventEmitter
2 def initialize
3 @listeners = Hash.new { |hash, key| hash[key] = [] }
4 end
5
6 def on(event, &block)
7 raise ArgumentError, "a block is required" unless block_given?
8
9 @listeners[event] << block
10 block
11 end
12
13 def once(event, &block)
14 wrapper = nil
15 wrapper = lambda do |*args|
16 off(event, wrapper)
17 block.call(*args)
18 end
19 @listeners[event] << wrapper
20 wrapper
21 end
22
23 def off(event, handler)
24 @listeners[event].delete(handler)
25 @listeners.delete(event) if @listeners[event].empty?
26 end
27
28 def emit(event, *args)
29 return false unless @listeners.key?(event)
30
31 @listeners[event].dup.each do |listener|
32 listener.call(*args)
33 end
34 true
35 end
36
37 def listeners(event)
38 @listeners[event].dup
39 end
40end
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A Hash with a default block lets you append to per-key collections without checking existence first.
- 2Capturing a lambda in a variable it references lets the callback unregister itself when it runs.
- 3Duplicating a collection before iterating protects you from listeners that mutate it mid-loop.
Related explainers
ruby
class ToastBroadcaster include ActionView::RecordIdentifier def self.broadcast_to(user, message:, type: :notice)
How Turbo Stream toasts broadcast in Rails
turbo-streams
service-object
real-time
Intermediate
6 steps
javascript
const ROLE_PERMISSIONS = { admin: ['users:read', 'users:write', 'billing:read', 'billing:write'], manager: ['users:read', 'billing:read'], member: ['users:read'],
Role-based permissions middleware in Express
authorization
middleware
rbac
Intermediate
9 steps
ruby
class TemplateInterpolator PLACEHOLDER = /\{\{\s*([\w.]+)\s*\}\}/ def initialize(strict: false)
Interpolating templates with dotted keys in Ruby
regex
string-interpolation
hash-traversal
Intermediate
6 steps
ruby
class KeyTransformer def self.camelize(data) new.camelize(data) end
Recursively camelizing nested Ruby data
recursion
data-transformation
pattern-matching
Intermediate
7 steps
ruby
module Paginatable extend ActiveSupport::Concern private
A reusable pagination concern in Rails
pagination
concerns
http-headers
Intermediate
8 steps
ruby
class Api::MessagesController < ApiController before_action :authenticate_api_key! rate_limit to: 100,
Layered API rate limiting in Rails
rate-limiting
api-authentication
throttling
Intermediate
9 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/building-an-eventemitter-in-ruby-explained-ruby-1f53/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.