From 7de0e70d7875b6ca0774c99e5da49b1f8b75c998 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Fri, 17 Apr 2026 10:51:31 -0400 Subject: [PATCH] Add Define A Set Of Class Methods as a Ruby TIL --- README.md | 3 +- ruby/define-a-set-of-class-methods.md | 46 +++++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 1 deletion(-) create mode 100644 ruby/define-a-set-of-class-methods.md diff --git a/README.md b/README.md index 7765fb9..8db5b61 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ working across different projects via [VisualMode](https://www.visualmode.dev/). For a steady stream of TILs, [sign up for my newsletter](https://visualmode.kit.com/newsletter). -_1776 TILs and counting..._ +_1777 TILs and counting..._ See some of the other learning resources I work on: @@ -1420,6 +1420,7 @@ If you've learned something here, support my efforts writing daily TILs by - [Defaulting To Frozen String Literals](ruby/defaulting-to-frozen-string-literals.md) - [Define A Custom RSpec Matcher](ruby/define-a-custom-rspec-matcher.md) - [Define A Method On A Struct](ruby/define-a-method-on-a-struct.md) +- [Define A Set Of Class Methods](ruby/define-a-set-of-class-methods.md) - [Define Multiline Strings With Heredocs](ruby/define-multiline-strings-with-heredocs.md) - [Destructure The First Item From An Array](ruby/destructure-the-first-item-from-an-array.md) - [Destructuring Arrays In Blocks](ruby/destructuring-arrays-in-blocks.md) diff --git a/ruby/define-a-set-of-class-methods.md b/ruby/define-a-set-of-class-methods.md new file mode 100644 index 0000000..8be3f32 --- /dev/null +++ b/ruby/define-a-set-of-class-methods.md @@ -0,0 +1,46 @@ +# Define A Set Of Class Methods + +The most common way to define class methods is by defining them directly with +`self` (the class in the current context) on a method by method basis: + +```ruby +class User + def self.find_by(attrs) + # lookup logic ... + end +end +``` + +If you have a group of class methods you want to define, you can stick them all +within a `class << self` block which does similarly defines each of them as +singleton methods of that class (`User` in this case): + +```ruby +class User + class << self + def find_by_email(email) + # lookup logic ... + end + + def find_by_last_name(last_name) + # lookup logic ... + end + end +end +``` + +This opens the singleton class of `User` for modification, adding these two new +methods. + +We can see those defined alongside all other direct and inherited class methods: + +```ruby +> User.methods +=> +[:find_by_email, + :find_by_last_name, + :yaml_tag, + :allocate, + ... +] +```