ruby

Search users as you type in Ruby on Rails with htmx

Accepting nested attributes in Ruby on Rails

Post like / unlike with htmx on Rails - partial replacement, server-side rendering

Authorization concerns for models and controllers in Ruby on Rails

Rails Trackable Concern: Automatically Set Created By

The Trackable concern automatically assigns the created_by field when a record is created, using Current.user. This keeps model logic clean while ensuring proper tracking of record ownership. The Post model includes Trackable, to get this functionalit

Detecting and storing user's timezone in Ruby on Rails automatically

This snippet automatically detects and stores a user's timezone by capturing it in JavaScript and saving it in a cookie. On every request, Rails reads this value and updates the user’s timezone in the database if needed. The local_time method then all

Rails Callback: Automatically Normalize Usernames Before Save

This snippet ensures usernames are consistently formatted by automatically trimming spaces and converting them to lowercase before saving. The before_save callback in the User model prevents duplicates caused by case differences. The UsersController h

Ruby on Rails custom validator to validate HEX color format

This snippet defines a custom validator for hex color codes, ensuring that values follow the correct #RGB or #RRGGBB format. By using ActiveModel::EachValidator, the validation logic remains reusable across multiple models. This approach keeps models

Rails Background Jobs with ActiveJob and Sidekiq

Background jobs improve performance by offloading time-consuming tasks like sending emails. This snippet uses ActiveJob with Sidekiq to send a welcome email asynchronously. The SendWelcomeEmailJob finds the user and triggers the mailer, while the User

Rails ActiveStorage: Attach and Display Images Easily

This snippet enables a User model to attach an avatar image with just has_one_attached :avatar. The view logic checks if an avatar exists and displays it using image_tag. This approach avoids complex file storage logic, letting Rails handle uploads se

Ruby on Rails Concern for Soft Deletable Records Without Losing Data

Rails Email Domain Validation: Restrict to Approved Domains

This custom EmailDomainValidator ensures users can only register with emails from approved domains. It extracts the domain from the email and checks it against a predefined list. The User model applies this validation. A challenge is making the allowe