Write Software, Well

Archive

Going Enterprise

For the past two years, I've been working with a client, an enterprise software company, and it has opened up a whole new world for me. There's so much I didn't know, and so much that can be made better. So going forward, enterprise software is what I'll be learning and writing about.

How to Safely Drop Columns in Rails

Dropping a column is simple in syntax but risky in production. Between running the migration and restarting the app, the old process still serves traffic with a cached schema, and can cause errors in production. Rails' ignored_columns fixes this by telling ActiveRecord to stop using a column before you actually drop it.

Refactoring Databases (in Rails)

These are my notes from the first few chapters of Refactoring Databases by Scott Ambler and Pramod Sadalage. The book was published in 2006 and its examples are a bit outdated, but the underlying ideas translate well to modern Rails applications where migrations serve as the primary mechanism for schema evolution. A follow-up post will cover additional database refactoring techniques from the later chapters.

Finally, the Rails Blog Runs on Rails

Last year, I announced plans to rewrite this blog in Ruby on Rails. It was hosted on Ghost for all these years (which is built with Node.js), and the idea was to rebuild it from scratch in Rails and write about the process as I went along. I even published a few posts as I started development.

You Can Now Access Bearer Tokens Directly from Request

The new bearer_token method on the Request object is a nice addition to Rails. It removes boilerplate code and simplifies bearer token extraction. All Rails apps can now access bearer tokens the same way without having to write custom token extraction logic every time and worrying about edge cases.

Combined Credentials in Rails 8.2

Rails 8.2 adds support for combined credentials, a unified API that checks environment variables first, then falls back to encrypted credentials, with consistent behavior for nested keys, defaults, and error handling. It's also possible to use your own combined configuration.

Active Storage Internals: How has_one_attached DSL Works

In this post, we'll explore the internals of has_one_attached method in Active Storage. It covers two interesting patterns, i.e. proxy and change objects. We'll trace the control flow from the model DSL to persistence and uploads, and explain how files are created, detached, and purged.

Active Storage Domain Model: Blobs and Attachments

Active Storage uses two main models: blobs and attachments. Blobs store the uploaded file's metadata and a link to the actual file, while attachments link those files to records. Understanding how they work together makes it easier to manage uploads, generate URLs, and process uploaded files.

Rails on Localhost: Secure Context and Local HTTPS with Caddy

Localhost is treated as a trustworthy origin even without TLS, so all apps on localhost run in a secure context. This allows secure features to work in development. You can also run multiple apps on localhost with subdomains + ports to separate them. When you do need local HTTPS, use Caddy server.

Sitemaps: A Quick SEO Win for New Websites

A sitemap lists your site's pages, helping Google crawl it efficiently. It's especially useful for large sites or new sites with zero backlinks. This post shows how you can create one in your Rails site, how to add it to Google Search Console, and how to index new pages as soon as you publish them.

Polymorphic URLs with direct Router Helper

The Rails router's direct method lets you create custom url and path helpers, which is especially useful for polymorphic models and delegated types. This post shows how to use a single custom helper to generate URLs for different models, with a practical example from the open source Maybe project.

Working Effectively with AI as a Developer

I started as a sceptic, but now I'm a convert and a heavy user of AI for everyday programming, and wanted to write down some common patterns and prompts for working with AI tools that I’ve found useful in my own development workflow as well as those I learned from other experienced developers.

Thoughts on Freelancing for Web Developers

After three years of freelancing and over a year of running my own software studio, here're some scattered thoughts on freelancing as a software developer, especially around web development.

Redirects in Rails: Manual, Helper, and Internals

In this post, we’ll explore how redirects work in Rails: what they are, how to redirect manually, and how the redirect_to method simplifies things. We’ll cover common use cases, security considerations, and even dig into the Rails source to see how redirect_to works under the hood.

Understanding the Render Method in Rails

In this post, we'll learn how Rails' render method works and how to use it effectively. From rendering templates, partials, and inline content to JSON and custom status codes, this post explores the different ways to render views from your controllers.

Vibe Learning is Underrated

Last week, I used AI to finally learn the basics of QuickBooks and handle my company’s bookkeeping. AI didn’t just help me finish a chore, it taught me a skill I’d been avoiding for years. When used with intent, the modern AI tools can accelerate your learning in surprising ways.

Serving Large Files in Rails with a Reverse Proxy Server

If your Rails app deals with large files, let a reverse proxy like Nginx or Thruster serve them. In this post, we'll learn how X-Accel-Redirect (or X-Sendfile) header hands off file delivery to Nginx. We'll also read Thruster’s source code to learn how this pattern is implemented at the proxy level.

Fix N+1 Queries Without Eager Loading Using SQL Subqueries

In this post, we'll learn how to use a SQL subquery in a Rails app to eliminate N+1 queries and improve performance. We'll profile a real-world example, showing how to fetch a single record from associated has_many records efficiently without eager loading or excessive memory usage.

Reduce Memory Usage by Selecting Specific Columns

As your application grows, so do your database tables. If you keep fetching all columns, those extra fields, especially large text or JSON blobs can quietly eat up a lot of memory. This post shows how to reduce memory usage in your Rails apps by selecting only the columns you need from the database.

Profiling Ruby on Rails Applications with Rails Debugbar

This post shows how you can get a better understanding of your Ruby on Rails application performance with the Rails Debugbar, a profiling tool inspired by Laravel Debugbar. It also covers how to spot N+1 queries, reduce object allocations, and optimize SQL queries to improve page load times.

Why You Need Strong Parameters in Rails

In 2012, GitHub was compromised by Mass Assignment vulnerability. A GitHub user used mass assignment that gave him administrator privileges to none other than the Ruby on Rails project. In this post, I will explain this vulnerability and how you can use the Rails strong parameters API to address it.

Working with HTTP Responses in Rails

In this post, we'll learn how to work with the response object in Rails controllers — from inspecting response bodies and headers to setting status codes and content types. This guide also covers key methods like body, status=, content_type, cookies, and more, with practical examples.

Working with HTTP Requests in Rails

Every web application needs to process incoming HTTP requests. In this post, we’ll take a closer look at how Rails handles requests, how you can access the request object in the controller, and some of the most useful methods it provides to gather meaningful data from the request.

Understanding Rails Parameters

Rails parameters let you access data sent by the browser, both via the URL and forms. In this article, we'll cover the basics of parameters, including what they are, how they work, and why they're important. We'll also learn how you can pass parameters in different formats such as arrays and hashes.

New Series on Rails Controllers

This is the first post in a new series that explores the Rails controllers in detail. This post covers the basics, providing a brief overview of controllers, why we need a controller, and how to create one. We'll start exploring more advanced stuff about controllers starting from the next post.

Restrict Destroying Dependent Rails Associations with Error

The `dependent: :restrict_with_error` option is a simple way to enforce data integrity in Rails apps. By preventing deletions of parent records with existing associations and providing helpful errors, it ensures historical data remains intact while guiding users on how to handle dependencies properly.

Backup SQLite from a Containerized Rails App Deployed with Kamal

This post walks through backing up a SQLite database inside a Docker container on a remote server, specifically for a Ruby on Rails application deployed with Kamal. We'll begin with the basic commands, then convert them into a reusable shell script and a Rake task for convenience.

Working with the Rails Instrumentation API

The Instrumentation API in ActiveSupport serves a dual purpose. You can use it to implement the observer (pub-sub) pattern, as well as benchmark how long it took to execute some action. In this post, we'll learn almost everything you need to know about the Rails Instrumentation API.

Using Hotwire for Inline Form Updates Without Form Submission

Sometimes you need dynamic content on the form, where parts of the form update based on the user input. This post shows how to use Hotwire's Turbo and Stimulus libraries for in-place form updates by loading data from the server, without submitting the form, which happens only once, at the end.

Not-Null Shortcut in Rails 8 Migration Generator

Rails 8 lets you mark a database column as not-null by appending an exclamation mark after the column while generating a migration. It's a nice quality of life improvement. This post also contains a few things I learned after reading the pull request.

If You're a WordPress Developer, Learn Ruby and Rails

With the recent WordPress drama, many developers might be concerned about its future. While WordPress isn't likely to go away, now might be the perfect time to invest in learning other tools and technologies. I suggest Ruby on Rails - you won't regret it!

How to Count the Number of Commits After a Specific Commit in Git

Counting the number of commits after a specific commit in Git is a common task when you make small but frequent commits and need to squash them before rebasing from the main branch. This post shows one simple way to do this in git. Let me know if you know a better solution.

The Rails Router Handbook

For the past few days, I've been trying to learn everything I could about the Rails router. I compiled all of my notes together with the past articles on this blog, and published a handbook on the router. I hope you find it useful and you learn a thing or two about the incredible Rails Router.

Routing Concerns in Rails

You must have used concerns in Rails. Did you know you can also use concerns for your routes? They allow you to declare common routes to be reused in other resources and routes. This post covers the basics of routing concerns, including what they are, how they work, and when you might need them.

Understanding Shallow Nested Routes in Rails

One way to avoid deeply nested routes in Rails is to use shallow nesting. This means you keep the routes that list or create records scoped under the parent resource, so the relationship is clear. But for routes that act on a specific record, you don’t include the parent in the URL. Instead, you use only what’s necessary to uniquely identify that record, which keeps routes shorter and easier to work with.

Working with Resourceful Routes in Ruby on Rails

The concept of resourceful routing took me a long time to understand, but once it clicked, it changed how I viewed web applications. This post covers the basics: what a resource is, the routes it generates and how resourceful routing provides a nice organizational structure your Rails applications.

How to Route an Incoming URL to a Rack Application in Rails

The Rails router can dispatch an HTTP request to a Rack endpoint, either in your application or within a gem. This is useful when you want to provide a well-isolated web UI or front-end to the users of your gem. In this post, we'll learn why you may want to do this, how it works, and how to do it.

Working with Nested Resources in Ruby on Rails

Nested resources in Rails model parent–child relationships in routes, like comments under posts. They make intent clear and improve semantics, but should be used sparingly. Shallow nesting keeps URLs readable and controllers simpler.

How to List and Filter Routes in Ruby on Rails

This post shows how you can list all the routes in your Rails application and find or filter them using the grep option. You can list all the routes in your Rails application by running the `bin/rails routes` command in the terminal. or by visiting `/rails/info/routes` path on a running Rails application.

Understanding the Match Method in Rails Router

In this post, we will learn about the match method, which forms the core of the Rails router. We'll also explore how the match method works behind the scenes. Once you really understand the match method and its options, the rest of the routing methods and shorthands become very easy to understand.

How to Override the Named Route Parameter ID in Rails

Rails generates URLs using the to_param value on models by default, which returns the id. By overriding to_param and adjusting your route segment (for example to :slug), you can replace the id with any meaningful value like a slug in your URLs.

Understanding Named Routes in Rails

In this post, we'll learn how named routes work in Rails. You can name a route by passing the as option. The router will create two helper methods based on this name to generate the URLs for the route.

How to Add a root Route in Rails

This post shows how to configure a root route for your application. This is the page your visitors will encounter the first time they visit your Rails app.

How to Access Raw POST Data in Rails

This post shows how you can access the raw, unaltered request body using a 20-year old method in the Rails framework (from the founder of Shopify). The `raw_post` method reads the request body, and is useful for web services or API controllers that need to directly work with raw requests.

Rails Router: Dynamic Segments and Query Strings

Rails routes aren’t just static paths. Dynamic segments let you capture values directly from the URL, while query strings handle optional parameters. This post explains how Rails parses both, when to use each, and common pitfalls to avoid.

Polymorphic Associations in Rails: Why, What, and How

Polymorphic associations in Rails allow a single model to belong to multiple models. This article covers them in-depth. We'll start with understanding the concept of polymorphism, learn what a polymorphic association is, why we need them, how they work, and how to use them in your Rails application.

A Brief Overview of the Rails Routing Config File

The Rails routing file defines how incoming requests map to controllers and actions. This post breaks down config/routes.rb, explains resourceful routes, nesting, and constraints, and shows how small routing choices affect clarity, URLs, and long-term maintainability.

My Notes from Shape Up: Shipping Work that Matters

This post contains my notes and highlights from the Shape Up from 37signals. It contains practical and actionable advice on project management, planning, and actually shipping meaningful work. I found it a great alternative to traditional practices like Agile. Give it a try on your next project!

How to Setup Rails-like Integration Tests in Ruby

In this next post in the Rails Companion series, we'll add support for integration testing to our Ruby web application. Specifically, we'll set up the Minitest framework and simulate HTTP requests using the rack-test gem. Finally, we'll add some syntactic sugar to make our tests just like Rails.

How to Access Rails Models in a Rake Task

This article shows how you can access your application models and other constants inside rake tasks by adding the `environment` task as a dependency. We'll also go one level deeper and learn exactly how this task loads the environment by inspecting the Rails source code.

I am Available as a Freelance Developer

With my current projects wrapping up, I have the capacity to take on at least one or two new freelance projects, and I can devote my full attention for 20-30 hours each week per project. If you (or your team) are looking for a freelance Ruby and Rails developer, please reach out to me via email.

From a Lorry Driver to Ruby on Rails Developer at 38

I recently had the pleasure to interview Pedro David Garcia Lopez, a Ruby and Rails developer based in UK, who used to be a Lorry driver. What's interesting is that he decided to become a developer at the age of 38. This post shares his story and I hope you find it as inspiring as I did!

How I Read Rails Source Code

Here're two techniques I've found really helpful for reading the Rails codebase, without getting overwhelmed. If you want to dive into the Rails source code for a deeper understanding, but feel intimidated by the sheer size of the codebase and don't know where to begin, this post is for you.

Build Your Own Router in Ruby

Have you always wondered what a Router is and how it works? I know I have. In this second bonus post in my Rails Companion course, we'll build our own router in Ruby to get a deeper understanding of the Rails Router. We'll also use some meta-programming to make it look just like the Rails router.

Growing Object-Oriented Software, Guided by Tests

Testing software is good. Period. This book gives a practical approach to building software combining the principles of object-oriented programming with test-driven development. All the buzzwords might trigger your inner sceptic, but this book is really, really good. Highly recommended.

Understanding Ruby's defined? Keyword

Ruby's defined? keyword is an elegant way to check if a variable is defined or not and also to cache expensive operations. However, it's confusing, and a few gotchas await the new Rubyist. Now that I've had a few opportunities to play with it, here’s my shot at sparing you some of the confusion.

Honeybadger Now Supports Logging and Event Monitoring

Honeybadger recently added support for logging and event monitoring. It's one feature that I've been waiting for a while now, and I recently stumbled upon it randomly yesterday. This post shows how you can log events from your Rails apps to Honeybadger.

Let's Build a Web Application in Ruby without Rails

Rails is great for building web apps. But it can be quite overwhelming if you don't know how web applications work. In this series of articles, we'll build a simple but complete app in plain Ruby without Rails, to get a deeper understanding and appreciation of everything Rails does for us.

What Does the Frozen String Literal Comment Do in Ruby?

Frozen strings not only prevent unintended modifications, but also reduce the overhead of the garbage collector by eliminating unnecessary memory allocations, thus improving application performance. This post explains the concept of freezing along with the magic comment frozen_string_literal.

Speed Up Your Tests Using VCR Gem in Ruby

HTTP API requests can be slow. They're especially slow if you have to make them repeatedly in your tests. The VCR gem in Ruby speeds up your tests by recording the response the first time and replaying the same response for future runs. Let's understand how it works and how to use it.

Playing Sounds in Rails with the Audio API

In this post, we'll learn how Campfire allows users to play various funny sounds by typing `/play` followed by the name of the sound. I found the entire flow pretty interesting, involving various aspects of Rails and Hotwire. Let's see how it's done.

How to Generate Random Numbers in Ruby

This post covers the basics of random number generation in Ruby. As with everything in Ruby, there're multiple ways you could do it, with some approaches better than the other. We'll also explore generating random numbers in various formats as well as generating secure random numbers.

Anonymous Block Forwarding in Ruby

In this post, we'll take a look at the anonymous block forwarding feature added in Ruby 3.1. It lets you replace your execute(&block) calls with execute(&). Not only it saves you from coming up with a variable (most likely blk), it also looks pretty sweet. I dig it.

Custom URL Helpers in Rails with the direct Method

This is the first post in the Campfire deep dive series where we explore the first ONCE product from 37signals to learn and extract useful patterns, ideas, and best practices. This post explores the direct method in the Rails Router that lets you define custom URL helpers for your application.

Understanding the Rails Router: Why, What, and How

The router is the entry point of your Rails application. It acts as the gatekeeper for all incoming HTTP requests, inspecting and sending them to a controller action; even filtering and rejecting them if necessary. In this article, we’ll do a deep dive into the Rails Router to understand it better.

What is __FILE__ in Ruby?

You must have come across the mysterious term __FILE__ while reading Ruby code. It's a magic variable that returns the name of the current file. This short post shows a few different use cases that I found while reading the Rails source code.

Understanding How Rails Environments Work

This post covers the basics of environments in Rails, including what they are, how they work and why they're so important. We'll also take a look behind the scenes and dive into the Rails source code to learn exactly how they're implemented, exploring a few interesting "inquiry" classes in Rails.

Learn to Program Ruby with Me

Any topic, no matter how basic, can be made much more interesting if you dig deep enough, and we can always improve, grow, and extract more out of our education. This post announces a new tutorial on this blog where we'll learn to program in Ruby from the absolute basics. Hope you join me.

How to Process a Turbo Stream Response in JavaScript using Stimulus

It’s common to make HTTP fetch request to get some data from the server. It’s also convenient to update the HTML via Turbo Stream responses. What if you could combine the benefits of them both? This post shows you how to process Stream responses in JavaScript, without mucking around with the DOM.

The Rails Config File

You must have used a `~/.bashrc` or `~/.zshrc` file to configure your environment. Did you know Ruby on Rails has a `~/.railsrc` file that configures your Rails applications? Not only that, it lets you pre-configure the gems you want in all your Rails applications. This post shows how it works.

See Other After Destroy

This post explains why you should use the 303 See Other HTTP status after destroying a resource, instead of using 302 Redirect.

How to Remove Whitespace from a String in Ruby

Often, you want to sanitize a string variable by removing all leading and trailing whitespaces around it. This is usually needed when you receive the string input from a user or an external source. This post shows you how.

Annual Blog Review: 2023

Every year, I do a personal annual review. This year, I thought why not do the same for my blog, since it has become such an integral part of my life, both personal and professional. This post contains some of the highlights and a list of all the articles I wrote in 2023.

Enqueue Multiple Jobs Together with perform_all_later in Rails

Are you still looping over the list of jobs to enqueue them individually? This post explores the new `perform_all_later` method in Rails, which was introduced in Rails 7.1 and lets you enqueue multiple jobs together to reduce the round-trip to the job backend, like Redis or the database.

Nested Modules in Ruby

There are two different ways to define nested modules in Ruby. This post explains them both along with the differences between them and how to decide which one to use. We will also learn about the `Module.nesting` method, which returns the list of nesting for a module.

How to Read a File in Ruby

Reading a file is a simple yet common programming task that can be accomplished in a few different ways in Ruby. In this post, we're going to cover the basics of reading files in Ruby, including few different ways to open and read files, both in-memory and via streaming.

Rails Internals: A Deep Dive Into Active Job Codebase

Do you want to understand how Active Job works behind the scenes? Reading and understanding the source code is one of the best ways to learn a framework (or anything). This post breaks it all down for you by tracing the journey of a Rails background job, from its creation to execution.

Working with SQLite in Ruby

SQLite is an incredibly simple yet powerful database both for beginners and advanced users to learn SQL as well as build applications (both desktop and web) that need to store data. In this post, we're going to cover the basics of working with SQLite in Ruby.

How respond-to Method Works in Rails

The respond_to method allows the controller to select the appropriate response format based on the request's Accept header or the request URL. You can also use it to handle variants for different screens. This post covers the basics of this method: what it is, how it works and why it's important.

CDPATH: Easily Navigate Directories in the Terminal

The CDPATH environment variable lets you pre-configure frequently used directories so you can easily navigate into them from anywhere in your file system. This blog post shows how it works and how to use it.

How to Return 404 Not Found Error in Rails

In this post, we'll learn about the HTTP 404 Not Found error: what it is and how it works, how to return a 404 response from a Rails application with a custom error page, and understand the impact of 404 errors on the SEO for your website or web application.

Interview with Daniela Baron, Staff Engineer at FundThrough

I recently had the pleasure to interview Daniela Baron, a Ruby and Rails developer and staff engineer at FundThrough, a fintech company based in Toronto. It contains a lot of interesting and thoughtful answers as well as a ton of high-quality recommendations for books and podcasts. Enjoy!

Akshay's Blog is now Write Software, Well

This blog is about writing as much as it is about software development. After two years, 130 posts, and hundreds of thousands of readers, the blog has outgrown my personal domain and needs a new home. Welcome to "Write Software, Well".

Base64 Encoding, Explained

Base64 is an elegant way to convert binary data to text, making it easy to store and transport. This article covers the basics of Base64 encoding, including what it is, how it works and why it's important. It also shows how to encode and decode Base64 data in various programming languages.

Length, Size, and Count in Ruby and Rails: When to Use Which?

You can use the length, size, and count methods to find the number of elements in a collection. This post explores the difference between these methods and explains how you should choose which method to use according to the needs of your application.

Interview with Miles Woodroffe, former Global CTO of Cookpad

Miles Woodroffe is a veteran Ruby & Rails developer who served as a Global CTO at Cookpad for many years and represents the company as a founding board member at the Rails Foundation. I recently had the pleasure to interview Miles, and he graciously provided very thoughtful and interesting answers.

The Difference Between nil?, empty?, and blank? in Ruby

In Ruby, you can use nil? method to check if the object is nil. However, Ruby also provides empty? and there’s a blank? method in Rails. For a Ruby (or Rails) newbie, it can get quite confusing, it certainly did for me. This post explains which method to use when. Hope it simplifies things a little.

Refactoring: Improving the Design of Existing Code (My Notes and Highlights)

I recently re-read Martin Fowler's excellent book on refactoring. It's about improving the design and quality of your code in small steps, without changing external behavior. The book contains detailed descriptions of refactorings, with motivation, mechanics, and an example for each. A must-read.

What Happens When You Run Rails dev:cache Command?

You can enable caching in development mode by running the `rails dev:cache` command in terminal. Ever wondered what that command does, and how exactly does it tell Rails to start caching stuff in your application? Let's take a peek behind the curtain to see exactly what's going on.

How to Debug and Step-Through Rails Codebase

Do you want to read the Rails source code for a deeper understanding of the framework, but feel intimidated by the sheer size of the codebase, or don't know where to start? Start with a specific feature, insert a breakpoint, and step through the method line-by-line. This article shows how.

The Complete Guide to Working With Cookies in Rails

This post covers almost everything you need to know about HTTP cookies in the context of Rails. We'll explore what a cookie is, why we need it, how to set & get a cookie, how to restrict cookies to a particular domain/path, prevent JavaScript access, how to sign & encrypt cookies, and much more.

Rails Middleware: (Almost) Everything You Need to Know

In this post, we'll learn almost everything about Rails middleware: what it is, why we need it, how it works, and why it's so important. We'll also learn how to create and test custom middleware in a Rails app. Finally, we'll extract logging functionality in its own middleware in a simple web app.

Let's Read the Turbo Source: What Happens When You Click a Link?

Reading the source code is one of the best ways to learn how a feature, framework, or a program works. In this post, we'll explore the source code of Hotwire's Turbo library to understand exactly what happens when you click a link. I hope you'll appreciate Turbo much more after this deep dive.

Let's Implement the Map Method from First Principles

Those new to functional programming often wonder when to use higher-order functions (or blocks/procs/lambdas in Ruby). I did, too. In this post, we'll implement the map method from scratch, in turn gaining an intuitive understanding of higher-order functions and when to use them.

Rails Database Migrations Cheatsheet

The database schema evolves continuously. Rails migrations is a powerful and flexible way to update the schema without dropping and re-creating the database. However, all this power and flexibility can be overwhelming. Here's a handy cheatsheet for most common migration operations.

Practical Stimulus: Building a Counter Component

In this article, we will build a counter component using the Stimulus JavaScript library. This simple example will demonstrate a bunch of useful features of Stimulus such as managing state, handling events, and targeting DOM elements.

Ruby's Hash is a Swiss-Army Knife

A Hash is a built-in data structure in Ruby that maps values to keys and has a constant-time O(1) lookup. This article shows the capabilities of this simple, but equally powerful tool. We’ll start with the basics but also cover some obscure but equally useful features of hash.

Abbrev: A Hidden Ruby Gem

The Abbrev module in the Ruby standard library helps you find out all the possible and unique abbreviations for one or more strings. In this post, we'll learn how it works along with a practical example. We'll also take a peek behind the scenes to see how it's implemented.

Using Zeitwerk Outside Rails

Did you know you can use Zeitwerk outside Rails? This article shows how to use the Zeitwerk gem to autoload classes and modules in a Ruby app that's not using Rails. We'll also learn how Rails configures Zeitwerk internally and introduce the concept of models in our no-rails Ruby web application.

How to Implement Content Security Policy in Rails

This article shows how to implement content security policy in your Rails applications to protect against cross-site scripting (XSS) vulnerability. We'll also learn how you can report CSP violations without enforcing the policy and make exceptions for inline scripts with nonce attributes.

You Don't Need Rails to Start Using Hotwire

Although Hotwire is closely tied to Ruby on Rails, you might be surprised to know that you don't really need Rails to learn, play, and experiment with Hotwire. In this article, we'll build a simple static site that uses Turbo Drive + Frames to make it responsive and use Streams to make it dynamic.

Content Security Policy (CSP): What Every Web Developer Must Know

This is a comprehensive guide to Content Security Policy (CSP). If you build websites for a living, CSP is an important concept to know, understand, and implement to protect your users from Cross-Site Scripting (XSS) Injection attacks. This post covers (almost) everything you need to know about CSP.

Serving Static Files in Ruby

This is the fourth article in the series where we build a simple, yet complete web app in plain Ruby, without using Rails to better understand how Rails works. In this article, we'll learn how to serve static files in plain Ruby, without using Rails.

Logging in Ruby: (Almost) Everything You Need to Know

Like backups, logging is one of those topics that seems unnecessary until something goes wrong! It's very frustrating to fix a bug that's only reproducible in production without having any logs to help you debug it. This post covers the basics of logging in Ruby and adds logging to our no-rails app.

How to Dynamically Create Instance Variables in Ruby

This post shows one way to dynamically initialize multiple instance variables in a Ruby class using metaprogramming. If you need to pass multiple, separate pieces of data to a constructor (and cannot refactor the code for some reason), it's a pretty good technique to reduce all the repetitive code.

How to Render SVG Icons in Ruby on Rails

This post shows how I render SVG icons in my Ruby on Rails applications. Instead of littering your HTML with complicated SVG tags, keep them tucked away in a folder as an ERB partial, and use a Rails helper to insert it in your views. Result: reusable, customizable icons and readable HTML.

How to Implement Rails-like Dynamic Views in Ruby

In this article, we will learn 'one' way to implement the controller-to-view data handoff using instance variables, just like Rails, and following the same conventions as Rails. Although it's a highly simplified implementation to keep things simple, I hope you'll find it fun and learn something new.

Implementing Rails-like Controllers in a No-Rails App

In its essence, a controller class in Rails is a coordinator. It accepts the incoming HTTP request and builds the data required by the view using the domain models. This post shows a highly simplified implementation of the controller pattern for a better understanding of Rails controllers.

Understanding the Concept of Binding in Ruby

Binding is an elegant way to access the current scope (variables, methods, and self) in Ruby. Typically, you use it for building view templates and executing strings of Ruby code. The Ruby REPL also makes abundant use of binding. In this post, we'll learn what binding is and how it works.

Practical Stimulus: Capture User Input

Stimulus is a JavaScript library that works really well with the HTML-over-the-wire approach of building web applications. In this series of articles, we'll learn how to accomplish common front-end tasks using Stimulus. This post shows how to capture user input and display it on the screen.

How Module Autoloading Works in Ruby and Rails

Autoloading allows you to speed up the initialization of your library by lazily loading the code only when you need it. This post explains how the autoload method works in Ruby and how Rails overrides this method to provide its own implementation that follows the Rails naming conventions.

Practical Stimulus: How to Toggle CSS Classes

This second article in the 'Stimulus in Practice' series shows how you can work with HTML classes using Stimulus. Specifically, we'll learn how to toggle classes on an element. This is useful when you want to show or hide certain elements or update the design in response to user interaction.

How to Create a Form with Multiple Submit Buttons to Different URL Endpoints

Although it's uncommon, there're a few cases where you need to submit a form to different endpoints. This post shows how you can create a form that has more than one submit buttons, each of which submits to a different URL endpoint. The formaction attribute on the button elements let you submit the form to a different URL endpoint. Additionally, you can use formmethod attribute to override the parent form's method.

How to Render Markdown Views in Rails

This article shows how to create and render markdown views in Rails. This is useful if you have a few static marketing pages in your web application that you'd like to save and edit as markdown along with the rest of your code files.

Concerns in Rails: Everything You Need to Know

Concerns are an important concept in Rails that can be confusing to understand for those new to Rails as well as seasoned practitioners. This post explains what concerns are, how they work, and how & when you should use them to simplify your code, with practical, real-world examples.

How to Create Custom Flash Types in Rails

While reading the Rails codebase last week, I came across a useful method that lets you create custom flash types. In this post, we'll learn how to use it and also how it's implemented behind the scenes. In the process, we'll also learn a few metaprogramming tricks in Ruby.

Inline Routes in Rails

If you want to quickly try out some Rails feature or code in the browser without spinning up a whole new controller and a view, simply map the incoming request to a lambda Rack endpoint, i.e. a lambda that returns the status, headers, and response body.

Simplifying My Blogging Workflow with Ruby

This is the 100th post on this blog 🎉 I wanted to share how a simple Ruby script simplified my blogging workflow and dramatically increased the number of posts I write on my various blogs.

Did You Know that You Can Catch and Throw Stuff in Ruby?

Unlike traditional programming languages, Ruby's throw and catch are not used to raise and catch exceptions. Instead, they let you escape from deeply nested control flows. This post shows how `throw-catch` works in Ruby with practical, real-world examples, including their usage by the Warden gem.

Various Ways to Run Shell Commands in Ruby

Ruby provides multiple ways to conveniently execute external processes from the code. In this article, we'll learn all the ways you can run shell commands in Ruby and also consider various circumstances under which you'd choose one over the other.

Ruby's Switch Statement is More Flexible Than You Thought

Ruby's switch statement is very versatile and flexible, especially due to the dynamic nature of Ruby. In this post, we'll see how you can use it in various ways. We'll also learn why it works the way it works. Hint: it uses the `===` operator (method) under the hood.

Can You Spot the Error?

I recently encountered this error and in the process of debugging, learned some useful stuff about `self` and how assignment works in Ruby. See if you can figure it out yourself. Can you spot the error in this simple Ruby snippet?

A List of Books to Learn Programming with Ruby and Rails

This post provides a curated list of books to learn to code in Ruby and build web applications with Rails. It also gives a step-by-step path you can follow to learn enough before moving to the next step. If you ever wanted to learn to program but didn't know where to start, this post is for you.

The Definitive Guide to Rack for Rails Developers

The word Rack actually refers to two things: a protocol and a gem. This article explains pretty much everything you need to know about Rack as a Rails developer. We will start by understanding the problem Rack solves and move to more advanced concepts like middleware and the Rack DSL.

Readonly Attributes in Rails

In this article, we'll learn how to mark certain attributes as readonly on your active record models, to prevent them from any future updates after the record is created and saved to the database. We'll also learn how Rails implements this feature behind the scenes.

Sessions in Rails: Everything You Need to Know

In this post, we’ll learn about Rails sessions, including what is a session, why we need them, and why they're so important. I’ll also take you behind the scenes and show you how Rails implements sessions and where the `session` method actually comes from. Hint: it’s not in the Rails codebase.

Progressive Application Development with Hotwire

This is the day when you fall in love with Hotwire. We're going to build a simple counter. But we're not going to build it once and be done with it. Instead, we'll build and progressively enhance it with all three frameworks in Hotwire: Turbo Drive, Turbo Frames, and Turbo Streams.

Configuring Rails Environments

Despite its strong opinions and powerful conventions, Rails is a highly flexible and configurable framework. If you don’t like something, there’s almost certainly a way to change it. This article provides a brief overview of configuring Rails applications and environments.

Turbo Streams: How They Work and Differ From Turbo Frames

No, you don’t need WebSockets to use Turbo Streams. You can simply use them to deliver multiple page updates with a single HTML response. This article teaches the basics of Turbo Streams to build a SPA without writing a single line of JavaScript. No Rails needed, either!

A Brief Introduction to Hotwire

Hotwire, which stands for HTML Over the Wire, provides a different way to build modern web applications without using too much JavaScript. This article provides a quick introduction to Hotwire and its component frameworks, such as Turbo Drive, Frames, and Streams.

Method Shorthand in Ruby

Ruby (3.0 and up) provides a shorthand syntax for one-line methods, similar to computed properties in C#.

class_eval vs. instance_eval in Ruby

This post explains the difference between class_eval and instance_eval methods in Ruby. If you keep getting confused between them when reading or writing Ruby code, it should clarify things a little.

Array Inquiry in Rails

The ArrayInquirer class provided by the Active Support framework in Rails provides a readable way to check the contents of an array. This post explores how you can implement this using metaprogramming in Ruby.

Tracking TODO and FIXME Comments with Rails Notes Command

This post shows how you can use the notes command in Rails to search through your codebase for comments starting with a specific keyword. By default, it searches the codebase for FIXME, OPTIMIZE, and TODO comments, but you can also configure it to use custom keywords.

Regular Expressions in Ruby

Regular expressions can be both terribly awkward and extremely useful. In this introductory post, we will learn the basics of regular expressions in Ruby programming language and how to use them for routine programming tasks.

Let's Learn Ruby on Rails + Hotwire by Building a To-Do List

In this article, we'll learn Ruby on Rails and Hotwire by building a to-do list from scratch. It shows how to build single-page web applications using traditional web architecture (server-rendered HTML), without the complexity of modern JavaScript frameworks like React.

How to Undo Generate Scaffold Command in Rails

Rails offers the convenient `rails destroy` command to undo the effects of any `rails generate` command. Also, don't forget to rollback the migration, if you have already applied it.

How self Keyword Works in Ruby

Ruby's self keyword can be pretty confusing to understand, especially if you're new to Ruby. Not understanding it often leads to subtle programming bugs that can be difficult to debug. This post explains how it works under common, everyday situations.

Setting Up Development Environment for Rails

This is the second article in the series on building awesome web applications with Ruby on Rails. It shows how to set up a kick-ass development environment for building Rails apps.

Define Custom Routes Using the Member and Collection Blocks in Rails

Let's say you want to add non-resourceful custom routes on your controller. Most often, you're better off by introducing a new resourceful controller. However, in those cases where you absolutely have to, you can define new routes using the member and collection blocks provided by the Rails router.

How &:method Shortcut Works in Ruby

This post shows you how Ruby's `&:method` shortcut works behind the scenes. It's a clever trick that was added first in ActiveSupport and became an official feature in Ruby 1.8.7.

Building Web Applications with Ruby on Rails

This is the first article in the series on building awesome web applications with Ruby on Rails. It explores why you should build for the web and use a web framework, especially Rails.

Compare Strings Using Inquiry

Similar to the ArrayInquirer class, which tests if an array contains a value, the ActiveSupport::StringInquirer class provides a nice way to compare two strings. Use it when you have an internal method that returns a string, and the consumer of that method needs to compare it with another string.

How to Access Variables Outside Scopes in Ruby

In C# and Java, variables from the outer scope are visible to the inner scope. In Ruby, scopes are sharply separated, and nested visibility is not allowed. As soon as the control enters a new scope, i.e. a class, module, or a method, the previous bindings are replaced by a new set of bindings.

Ruby is a Meritocracy

I recently read Russ Olsen's book Design Patterns in Ruby. In it, the author makes a wonderful distinction between statically vs. dynamically typed languages, which is different from all other comparisons I've seen.

How to Benchmark Rails Views

This post explores the Benchmarkable module provided by Active Support to measure the execution time for rendering Rails views.

How to Benchmark Ruby Code

The Benchmark module in the Ruby standard library helps you measure and report the time used to execute your code. This post explores three useful methods in this module, which allow you to measure and compare the execution times of code as well as warm up the code to stabilize the runtime environment.

Understanding Authenticity Tokens in Rails

This post explores CSRF vulnerability and how Rails mitigates it using authenticity tokens. We will will learn why they're needed, how they're generated, how Rails uses them to verify the requests, and how to disable them for specific requests.

Metaprogramming in Ruby

Metaprogramming in Ruby enables you to produce elegant, clean, and beautiful programs as well as unreadable, complex code that’s not maintainable. This book teaches you the powerful metaprogramming concepts in Ruby, and how to use them judiciously.

A Deep Dive Into Database Migrations in Rails

Like source code, database schema changes and evolves over time. Migrations are a feature of Active Record that allows you to manage the database schema changes gracefully, without writing any SQL. This post contains my notes on Active Record migrations from the official Rails guides.

Attributes API in Rails

Sometimes, you want to set default values on your ActiveRecord objects and convert them to a different type. Rails provides a handy attribute method that lets us do that, and much more. In this post, we will try to understand how to use the attributes API to achieve this.

How to Get the Current Absolute URL in Rails

Every Rails controller includes two accessor methods pointing to the request and the response objects associated with the current HTTP request cycle. The request method returns an instance of the ActionDispatch::Request class, which wraps the HTTP request and provides a nice API to inspect the request.

How to Rename a Database Column in Rails

Solution 1: Undo Last MigrationIf it is a simple typo in the last migration, use the db:rollback command to undo the last change. Then open the previous migration file, fix your typo, and rerun the migration. Make sure that no new data is inserted in the table or that no one on your team runs the stale migration.

Metal Controller in Rails

The ActionController::Base class is the great-grandfather of all Rails controllers, but doesn't get much attention. In this post, we will examine this Metal class and how it works. We'll also trace the path of an incoming HTTP request to Rails controllers.

Active Job: How does it work?

In this article, I explain the journey of a background job, from its creation to execution. We will learn how it’s configured and enqueued, and how an adapter invokes it. We will also see the different ways to configure a job.

Up and Running with Minitest

I love minitest. Minitest is simple. There’re a few ways to write tests, and they are so intuitive. I learned it last year, when I got into Ruby, and since then I haven’t really felt the need to dive into the docs that frequently. It just works.

Useful Linux Commands

“Learning the Linux command line, like becoming an accomplished pianist, is not something that we pick up in an afternoon. It takes years of practice.

How to Convert a Ruby Object to Hash

Let’s say you have a Product object with properties @name = "Table" & @price = 10. What’s the best way in Rails to convert this object to the Hash { name: "Table", price: 10 }?

Useful Ruby Gems

Although Rails provides great defaults out-of-the-box, you can easily extend it with Ruby gems. Here are some gems that I find myself using every time I start a new Rails project.

Why Turbo Uses Event Capturing

“💡 If you are interested in learning about Hotwire, check out my crash-course on Hotwire's Turbo framework.”

Why Choose `let` Over instance variables in RSpec

Repetitive setup code in tests makes it difficult to refactor the tests. It also distracts and shifts our focus from the business logic that we’re trying to test with the setup details. This post explains three ways to reduce the setup duplication in your tests.

Inline Edits using Turbo Frames

This post explains how to use Turbo Frames to make your web application behave like a Single-Page Application without using any JavaScript.

All the Database Tasks in Rails

Once you start programming in Rails, you inevitably come across db:migrate, which applies the migration to your database. Then you make a mistake and learn about db:rollback to revert the previous migration.

How to Drop a Table in Rails

So you created a migration to add a table that you thought you were going to need. You also ran that migration so that table is in your database. Now, you don’t need it anymore and want to drop it from the database. How do you remove that table?

How to Test Rails Source Code

One of the best ways to understand any codebase is to read the tests, and Rails is no exception. In this post, we will learn “how to run the tests” included in the Rails codebase.

Modifying Objects in Place

Every time you create or copy something in memory, you add work for GC. Here are some tips from the book Ruby Performance Optimization to write code without using too much memory.

Class Metaprogramming in Ruby

A Ruby class definition is just regular code that runs. When you use the class keyword to create a class, you aren’t just dictating how objects will behave in the future. You are actually running code.

How to Implement Callbacks in Ruby

There are at least three places in Ruby where you can package code to be executed later. In a block, a proc/lambda, and a method.

A List of Middleware Used by Rails

Here’s a list of middleware Rails uses in a development environment. You can view the middleware by running the bin/rails middleware command from your application directory.

Caching in Rails

These are the notes I took while reading the Rails caching guide.