Series: Today I Learned
A collection of concise write-ups on small things I learn day to day across a variety of languages and technologies. These are things that don’t really warrant a full blog post.
💡 TIL: Ruby can chain methods and right-assign #
I just learned that ruby supports re-writing this:
total = plus_shipping(with_taxes(subtotal(items)))
As:
subtotal(items).then { |subtotal| with_taxes(subtotal) }.then { |total| plus_shipping(total) } => totalfrom davetron
💡 TIL: Rails migrations can include an up_only part #
When writing a migration in Rails and you need to do one thing which can’t be automatically reversed, I always convert a def change to up and down. It turns out you can slip in an up_only block:
class AddFieldsToUsers < ActiveRecord::Migration[7.1] def change add_column :users, :first_name, :string add_column :users, :last_name, :string up_only do User.delete_all end end endfrom RubyCademy
💡 TIL: NASA’s Dragonfly probe to Saturn’s Titan in 2028 #
In 2028 NASA is launching a spacecraft to Saturn’s moon Titan to study its habitability in a mission named Dragonfly. It will land in 2034. They’re sending a drone powered by a radioisotope thermoelectric generator so they can visit a variety of sites. Titan is notable because it’s believed to have a similar chemistry to ancient earth. Past probes have measured the contents of the atmosphere and confirmed it contains a mix of hydrocarbons. The surface contains a lot of water ice and scientists believe there is a water ocean in the interior of the moon.
💡 TIL: Rails ActiveRecord has a .sole method #
I just learned about `sole` and `find_sole_by`. They ensure that only a single record is returned and will raise if there is something other than one. It’s the equivalent of:
api_keys = user.api_keys.where(key: key) if api_keys.length == 1 api_key = api_keys.first elsif api_keys.length == 0 raise "No records found!" else raise "More than one matching record found!" end
💡 TIL: pick is the single-value version of pluck in Rails #
Instead of doing
Messages.pluck(:user_id).firstyou can do
Messages.pick(:user_id)