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
class ContactImporter def initialize(rows) @rows = rows end
Deduplicating contacts with Enumerable#uniq
deduplication
normalization
enumerable
Intermediate
4 steps
ruby
class BulkImporter BATCH_SIZE = 500 def initialize(records)
Batching bulk inserts in Rails
batching
bulk-insert
deduplication
Intermediate
5 steps
ruby
class Credentials SENSITIVE = %i[password api_key secret_token access_key].freeze REDACTED = "[REDACTED]".freeze
Redacting secrets in Ruby object output
serialization
introspection
security
Intermediate
7 steps
ruby
module Multitenant extend ActiveSupport::Concern included do
How a multitenant concern scopes Rails models
multitenancy
default-scope
concern
Advanced
8 steps
ruby
module Api module V1 class BaseController < ActionController::API rescue_from StandardError, with: :render_internal_error
Centralized API error handling in Rails
error-handling
rescue-from
json-api
Intermediate
7 steps
rust
use std::sync::{Arc, Mutex, MutexGuard}; use std::time::Instant; pub struct TimedGuard<'a, T> {
A self-timing mutex guard in Rust
raii
mutex
deref
Advanced
7 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.