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

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

Authorization concerns for models and controllers in Ruby on Rails

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

Storing & querying IP addresses efficiently in Ruby on Rails

This snippet stores user IPs efficiently using the PostgreSQL inet type, which optimizes space and lookup speed. The from_same_network scope allows querying users within the same /24 subnet, useful for analytics or security checks. The update_ip metho

Adding polymorphic emoji reactions to any model in Ruby on Rails

This snippet introduces a polymorphic emoji reaction system in Rails, allowing models like Post (or any other) to receive emoji reactions. The Reaction model supports different reactable types via polymorphic: true. A simple emoji regex ensures valid

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

Automatically generate two-word slugs in Ruby on Rails

This snippet ensures every article gets a unique, readable slug based on its title, keeping it short and pronounceable. It grabs the first two words of the title and appends a 4-character random string to prevent duplicates. The before_validation call