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

Walkthrough

Space play step click any line
Three takeaways
  1. 1Prepending a module lets a wrapper run before the real method and call it via super, keeping instrumentation fully separate from logic.
  2. 2A method that returns an anonymous module is a factory for reusable, configurable behavior.
  3. 3ensure guarantees timing and logging fire even when the wrapped method raises.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Timing methods with a prepended module in Ruby in Rails — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code