Enumerable#each_with_object(memo)
igor-kasyanchuk / Underrated Ruby & Rails Features
Underrated Ruby & Rails Features
Unlock hidden gems in Ruby and Rails! This cheat sheet explores powerful, yet often overlooked, methods and features that can elevate your code quality, performance, and developer productivity, especially for experienced Rails developers.
Core Ruby Underrated Methods
Enumerable & Array Power-Ups
|
Iterates over an enumerable, yielding each element and a memo object. Useful for building complex data structures.
|
|
Splits the enumerable into chunks based on the return value of the block. Adjacent elements returning the same value are grouped.
|
|
Binary search on a sorted array. Returns an element or its index based on the block’s boolean or numeric result. Fast for large arrays.
|
|
Creates an enumerator that iterates over slices of the original enumerable. A new slice starts right before an element for which the block returns true.
|
|
Creates an enumerator over slices. A new slice starts right after an element for which the block returns true.
|
|
Counts the occurrences of each element and returns a hash. Simpler than
|
Object & Module Tricks
|
Yields the object to the block and returns the object itself. Useful for chaining methods while performing side effects or debugging.
|
|
Yields the object to the block and returns the result of the block. Useful for breaking down method chains or passing the result of one operation as an argument to another.
|
|
Invokes the method identified by
|
|
Provides a shortcut to define methods that forward to another object. Reduces boilerplate.
|
|
Returns a
|
|
Dynamically defines a method with the given name and block. Useful for metaprogramming.
|
String & Numeric Helpers
|
Reverses the effect of
|
|
Removes a record separator (like newline) from the end of the string, in place. Can take an argument to specify the separator.
|
|
Adds ‘a’ or ‘an’ prefix based on the number. Part of Active Support’s
|
|
Indents the string by the specified amount using the given indent string. Preserves existing newlines.
|
|
Removes leading and trailing whitespace and replaces internal sequences of whitespace with a single space. Part of Active Support.
|
|
Truncates a string after a certain number of words. More semantically useful than truncating characters.
|
ActiveRecord Deep Dive
Relation & Query Magic
|
Merges two relations. Useful for combining dynamic scopes.
|
|
Adds comments to the SQL query, useful for debugging and profiling tools to identify where queries originate.
|
|
Iterates over records in batches, processing them one by one (
|
|
|
|
Allows removing or keeping specific query clauses (
|
|
Removes conditions or scopes applied earlier in the chain, including default scopes.
|
Model & Class Methods
|
Suppresses specified exceptions within the block. Returns nil if an exception is suppressed, otherwise the result of the block.
|
|
Executes block within a database transaction. Can specify isolation level (
|
|
Inserts multiple records, updating them if a conflict arises (based on unique index). Highly performant for bulk insert/update.
|
|
Inserts multiple records in a single SQL statement. Much faster than creating individual records. Bypasses validations and callbacks.
|
|
Suppresses SQL logging within the block. Useful for noisy operations during tests or specific rake tasks.
|
|
Base class for defining custom attribute types. Allows casting, serializing, and deserializing complex data to/from database columns.
|
Data Handling & Efficiency
|
Enforces N+1 prevention. Any attempt to lazy-load an association on records from this relation will raise an error.
|
|
Iterates over batches of records. Provides a relation object for each batch, allowing further filtering/operations on the batch.
|
|
Generates a cache key based on the latest update timestamp, a list of IDs, and an optional column. Useful for caching collections.
|
|
Directly defines attributes backed by database types like
|
|
Returns a new instance of
|
Rails Beyond MVC Basics
Controller & View Rendering
|
Allows rendering views or templates outside of a controller context (e.g., in background jobs, mailers, console). Great for generating HTML snippets asynchronously.
|
|
A helper to build HTML tags more programmatically and safely than concatenating strings. Avoids raw HTML in helpers.
|
|
Allows rendering plain text responses easily, useful for simple API endpoints or health checks, bypassing template lookup.
|
|
Using
|
|
|
|
Though not strictly ‘underrated’, mastering its use for multiple formats (HTML, JSON, XML, JS, PDF, etc.) in complex actions is crucial for robust APIs and flexible controllers.
|
Configuration & Utility Helpers
|
A namespace for application-specific configuration settings. Defined in environment files (
|
|
Loads a YAML file from
|
|
|
|
Defines
|
|
Standard way to package shared functionality (methods, includes, callbacks) to be included in multiple classes. Improves code organization and avoids polluting the global namespace.
|
|
Searches code for comments like
|
Background Jobs & Mailers
|
The default job class used when you call
|
|
Built-in mechanisms for handling job failures.
|
|
Passing ActiveRecord objects directly to
|
|
Specifies the queue name for a job. Allows prioritizing or segregating jobs based on importance or resource requirements.
|
|
Allows developers to preview emails in the browser without sending them. Configure previews in
|
|
Configures mailers to store emails in
|