Code Explainers

Code explainers tagged #callbacks

ruby
class Comment < ApplicationRecord
  belongs_to :post
  belongs_to :author, class_name: "User"
 

Live-updating comments with Turbo in Rails

turbo-streams callbacks associations
Intermediate 8 steps
ruby
class Comment < ApplicationRecord
  belongs_to :commentable, polymorphic: true, counter_cache: true
  belongs_to :author, class_name: "User"
 

How polymorphic comments work in Rails

polymorphic-association concerns counter-cache
Intermediate 8 steps
ruby
module SoftDeletable
  extend ActiveSupport::Concern
 
  included do

How a soft-delete concern works in Rails

concerns soft-delete scopes
Intermediate 8 steps
ruby
class Post < ApplicationRecord
  before_validation :generate_slug, on: :create
 
  validates :slug, presence: true, uniqueness: true

How a Rails model builds unique slugs

slugs callbacks validations
Intermediate 7 steps
ruby
class EventEmitter
  def initialize
    @listeners = Hash.new { |hash, key| hash[key] = [] }
  end

Building an EventEmitter in Ruby

pub-sub closures callbacks
Intermediate 7 steps
ruby
class Article < ApplicationRecord
  before_validation :generate_slug, on: :create
 
  validates :slug, presence: true, uniqueness: true,

How URL slugs work in Rails

callbacks validations slugs
Intermediate 7 steps
ruby
class ArticlesController < ApplicationController
  before_action :authenticate_user!
  before_action :set_article, only: %i[show edit update destroy]
  before_action :authorize_owner!, only: %i[edit update destroy]

How before_action filters guard a Rails controller

filters authorization callbacks
Intermediate 9 steps