Tuesday, 29th October 2024
💡 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
📝 Ruby Sorbet is too verbose, can the syntax be improved? #
Awhile back when I was ramping up on Typescript, I was leaning into the benefits of types. In the Ruby world, Sorbet is the most common way to add types so I gave that a shot. In the end, I ripped it out. I spent more time wrangling type checking then the time it spent catching bugs, and one of the issues was the verbose syntax. But recently I came up with a novel solution to this problem. First, here is the verbose syntax — you end up declaring all your arguments twice:
sig { params(name: T.untyped, nickname: String).returns(Integer) } def greet(name, nickname) puts "Hello, #{name}! Your nickname: #{nickname}" name.length end