ruby

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

Rails Enum for Clean and Readable Status Management

Managing statuses in a Rails model can become messy with hardcoded values, but enums provide a clean and readable way to handle them. This snippet shows how to define an enum in an Order model, making it easy to reference statuses with descriptive sym

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

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

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