ruby
42 lines · 7 steps
Timing methods with a prepended module in Ruby in Rails
A module factory generates timing wrappers that measure any named methods without touching their bodies.
Explained by
highlit
1module Instrumentation
2 module Timing
3 def self.[](*method_names)
4 Module.new do
5 method_names.each do |name|
6 define_method(name) do |*args, **kwargs, &block|
7 started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
8 begin
9 super(*args, **kwargs, &block)
10 ensure
11 elapsed = Process.clock_gettime(Process::CLOCK_MONOTONIC) - started
12 StatsD.timing("#{self.class.name.underscore}.#{name}", elapsed * 1000)
13 Rails.logger.debug(
14 format("[timing] %s#%s took %.2fms", self.class.name, name, elapsed * 1000)
15 )
16 end
17 end
18 end
19 end
20 end
21 end
22end
23
24class PaymentGateway
25 prepend Instrumentation::Timing[:charge, :refund]
26
27 def charge(account, amount_cents)
28 response = client.post("/charges", amount: amount_cents, source: account.token)
29 Charge.new(response.fetch("id"), response.fetch("status"))
30 end
31
32 def refund(charge_id)
33 response = client.post("/refunds", charge: charge_id)
34 Refund.new(response.fetch("id"))
35 end
36
37 private
38
39 def client
40 @client ||= HttpClient.new(base_url: ENV.fetch("GATEWAY_URL"))
41 end
42end
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Prepending a module lets a wrapper run before the real method and call it via super, keeping instrumentation fully separate from logic.
- 2A method that returns an anonymous module is a factory for reusable, configurable behavior.
- 3ensure guarantees timing and logging fire even when the wrapped method raises.
Related explainers
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
ruby
class UserAgentParser BROWSERS = [ [/Edg\/([\d.]+)/, "Edge"], [/OPR\/([\d.]+)/, "Opera"],
Parsing user-agent strings in Ruby
regex
pattern-matching
lookup-tables
Intermediate
8 steps
ruby
class LogAggregator BUCKET_FORMAT = "%Y-%m-%dT%H:%M" def initialize(entries)
Bucketing log entries by the minute in Ruby
aggregation
hashing
enumerable
Intermediate
5 steps
ruby
class WeeklySignupsReport DEFAULT_WEEKS = 12 def initialize(weeks: DEFAULT_WEEKS, source: User.all)
Building a weekly signups report in Rails
service object
aggregation
group by
Intermediate
7 steps
ruby
class ApplicationController < ActionController::Base EXPERIMENTS = { checkout_button_color: %w[control blue green], onboarding_flow: %w[control streamlined]
How A/B test cohorts are assigned in Rails
a-b-testing
cookies
hashing
Intermediate
8 steps
ruby
class SnippetHighlighter CONTEXT_RADIUS = 60 MAX_TERMS = 8
Building search-result snippets in Ruby
regular-expressions
text-processing
search
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/timing-methods-with-a-prepended-module-in-ruby-in-rails-explained-ruby-bbce/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.