This week in #dev (May 5, 2023)

Edited by Matheus Richard

Welcome to another edition of This Week in #dev, a series of posts where we bring some of the most interesting Slack conversations to the public.

Measuring Elapsed Time Correctly

Sara Jackson learned about Process::CLOCK_MONOTONIC. It should be used instead of system time updates when measuring elapsed time because it ensures that the measurement is accurate and not affected by system time updates.

start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)
end_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)

puts "Elapsed time: #{end_time - start_time}"

Secret Active Record Methods

Summer ☀️ shares a cool Active Record feature: using ! query methods to modify a query object in place instead of returning a new one. Let’s use distinct! as an example:

# distinct! modifies the current query object, while distinct creates a new query object:
my_query = User.all
#=> "SELECT DISTINCT \"users\".* FROM \"users\""

my_query = User.all
my_other_query = my_query.distinct
#=> "SELECT \"users\".* FROM \"users\""
#=> "SELECT DISTINCT \"users\".* FROM \"users\""

In fact, distinct is implemented by calling something similar to self.dup.distinct!, Summer ☀️ adds. This kind of pattern also exists for other Active Record query methods like where/where!, order/order!, joins/joins!, etc.


This edition was brought to you by: Sara Jackson, Sean Doyle and Summer ☀️. Thanks to all contributors! 🎉