Rack provides a minimal, modular, and adaptable interface for developing web applications in Ruby. By wrapping HTTP requests and responses in the simplest way possible, it unifies and distills the bridge between web servers, web frameworks, and web application into a single method call.
Where is it used?
Rails (built on Rack)
Sinatra and Hanami
Middleware development
What is a Rack-Based Application?
A Rack-based application is any Ruby web application that implements the Rack interface. This means the app must follow Rack’s simple calling convention:
app = Proc.new do |env|
['200', { 'Content-Type' => 'text/html' }, ['Hello, Rack!']]
end
This returns an array of three elements:
HTTP status code ('200')
Headers ({ 'Content-Type' => 'text/html' })
Response body (['Hello, Rack!'])
Example: Basic Rack Application
require 'rack'
app = Proc.new do |env|
['200', { 'Content-Type' => 'text/html' }, ['Hello, Rack!']]
end
Rack::Handler::WEBrick.run app, Port: 9292
Run it with:
ruby my_rack_app.rb
Open http://localhost:9292 in your browser.
Does Rails Use Rack?
Yes, Rails uses Rack. Rack serves as the interface between Rails and web servers like Puma or WEBrick.
How Rails Uses Rack
When a request comes in:
The web server (Puma/WEBrick) receives it.
The server passes the request to Rack.
Rack processes the request and sends it through Rails middleware.
After passing through the middleware stack, Rails’ router (ActionDispatch) decides which controller/action should handle the request.
The response is generated, sent back through Rack, and returned to the web server.
Check /design_studio/config.ru file in our Rails 8 app is responsible for starting the server.
You can actually run a Rails app using just Rack!
Create a config.ru file / use existing one:
require_relative 'config/environment'
run Rails.application
Run it using Rack:
rackup -p 4343
open http://localhost:4343/products
This runs your Rails app without Puma or WEBrick, proving Rails works via Rack.
Is Rack a Server?
No, Rack is not a server. Instead, Rack is a middleware interface that sits between the web server (like Puma or WEBrick) and your Ruby application (like Rails or Sinatra).
How Does Rack Fit with Web Servers Like Puma and WEBrick?
Puma and WEBrick support Rack by implementing the Rack::Handler interface, allowing them to serve any Rack-based application, such as Rails and Sinatra.
Puma and WEBrick are not built “on top of” Rack—they are independent web servers.
However, they implement Rack::Handler, which means they support Rack applications.
This allows them to serve Rails, Sinatra, and other Rack-based applications.
The Relationship Between Rack, Web Servers, and Rails
Rack provides a standard API for handling HTTP requests and responses.
Web servers (Puma, WEBrick, etc.) implement Rack::Handler so they can run any Rack-based app.
Rails supports Rack by implementing the Rack interface, allowing it to interact with web servers and middleware.
How Rails Supports Rack
Rack Middleware: Rails includes middleware components that process requests before they reach controllers.
Rack Interface: Rails applications can be run using config.ru, which follows the Rack convention.
Web Server Communication: Rails works with Rack-compatible servers like Puma and WEBrick.
Illustration of How a Request Flows
The browser sends a request to the server (Puma/WEBrick).
The server passes the request to Rack.
Rack processes the request (passing it through middleware).
Rails handles the request and generates a response.
The response goes back through Rack and is sent to the server, which then passes it to the browser.
So, while Rack is not a server, it allows web servers to communicate with Ruby web applications like Rails.
Adding Middleware in a Rails 8 App
Middleware is a way to process requests before they reach your Rails application.
How Does Middleware Fit In?
Middleware in Rails is just a Rack application that modifies requests/responses before they reach the main Rails app.
Example: Custom Middleware
Create a new file in app/middleware/my_middleware.rb:
class MyMiddleware
def initialize(app)
@app = app
end
def call(env)
status, headers, body = @app.call(env)
body = ["Custom Middleware: "] + body
[status, headers, body]
end
end
Now, add it to Rails in config/application.rb:
config.middleware.use MyMiddleware
Restart your Rails server, and all responses will be prefixed with Custom Middleware:
To attach multiple images to a Product model in Rails 8, Active Storage provides the best way using has_many_attached. Below are the steps to set up multiple image attachments in a local development environment.
1️⃣ Install Active Storage (if not already installed)
We have already done this step if you are following this series. Else run the following command to generate the necessary database migrations:
rails active_storage:install
rails db:migrate
This will create two tables in your database:
active_storage_blobs → Stores metadata of uploaded files.
active_storage_attachments → Creates associations between models and uploaded files.
2️⃣ Update the Product Model
Configuring specific variants is done the same way as has_one_attached, by calling the variant method on the yielded attachable object:
add in app/models/product.rb:
class Product < ApplicationRecord
has_many_attached :images do |attachable|
attachable.variant :normal, resize_to_limit: [540, 720]
attachable.variant :thumb, resize_to_limit: [100, 100]
end
end
You just have to mention the above and rails will create everything for you!
Variants rely on ImageProcessing gem for the actual transformations of the file, so you must add gem "image_processing" to your Gemfile if you wish to use variants.
By default, images will be processed with ImageMagick using the MiniMagick gem, but you can also switch to the libvips processor operated by the ruby-vips gem.
3️⃣ Configure Active Storage for Local Development
By default, Rails stores uploaded files in storage/ under your project directory.
Ensure your config/environments/development.rb has:
config.active_storage.service = :local
And check config/storage.yml to ensure you have:
local:
service: Disk
root: <%= Rails.root.join("storage") %>
This will store the uploaded files in storage/.
4️⃣ Add File Uploads in Controller
Modify app/controllers/products_controller.rb to allow multiple image uploads:
class ProductsController < ApplicationController
def create
@product = Product.new(product_params)
if @product.save
redirect_to @product, notice: "Product was successfully created."
else
render :new
end
end
private
def product_params
params.require(:product).permit(:name, :description, images: [])
end
end
Notice images: [] → This allows multiple images to be uploaded.
Meanwhile we are setting up some UI for our app using Tailwind CSS, I have uploaded 2 images to our product in the rich text editor. Let’s discuss about this in this post.
Understanding Active Storage in Rails 8: A Deep Dive into Image Uploads
In our Rails 8 application, we recently tested uploading two images to a product using the rich text editor. This process internally triggers several actions within Active Storage. Let’s break down what happens behind the scenes.
How Active Storage Handles Image Uploads
When an image is uploaded, Rails 8 processes it through Active Storage, creating a new blob entry and storing it in the disk service. The following request is fired:
Processing by ActiveStorage::DirectUploadsController#create as JSON
Parameters: {"blob" => {"filename" => "floral-kurtha.jpg", "content_type" => "image/jpeg", "byte_size" => 107508, "checksum" => "GgNgNxxxxxxxjdPOLw=="}}
This request initiates a database entry in active_storage_blobs:
This process triggers the ActiveStorage::DiskController, handling file storage via a PUT request:
Started PUT "/rails/active_storage/disk/eyJfcmFpbHMiOxxxxx"
Disk Storage (0.9ms) Uploaded file to key: hut9d0zxssxxxxxx
Completed 204 No Content in 96ms
Retrieving Images from Active Storage
After successfully storing the file, the application fetches the image via a GET request:
Started GET "/rails/active_storage/blobs/redirect/eyJfcmFpbHMiOxxxxxxxxxxfQ==--f9c556012577xxxxxxxxxxxxfa21/floral-kurtha-2.jpg"
This request is handled by:
Processing by ActiveStorage::Blobs::RedirectController#show as JPEG
The file is then served via the ActiveStorage::DiskController#show:
Redirected to http://localhost:3000/rails/active_storage/disk/eyJfcmFpbHMiOnsiZGxxxxxxxxxd048aae4ab5c30/floral-kurtha-2.jpg
Updating Records with Active Storage Attachments
When updating a product, the system also updates its associated images. The following Active Storage updates occur:
UPDATE "action_text_rich_texts" SET "body" = .... WHERE "action_text_rich_texts"."id" = 1
UPDATE "active_storage_blobs" SET "metadata" = '{"identified":true}' WHERE "active_storage_blobs"."id" = 3
INSERT INTO "active_storage_attachments" ("name", "record_type", "record_id", "blob_id", "created_at") VALUES ('embeds', 'ActionText::RichText', 1, 3, '2025-03-31 11:46:13.464597')
Additionally, Rails updates the updated_at timestamp of the associated records:
UPDATE "products" SET "updated_at" = '2025-03-31 11:46:13.523640' WHERE "products"."id" = 1
Best Practices for Active Storage in Rails 8
Use Direct Uploads: This improves performance by uploading files directly to cloud storage (e.g., AWS S3, Google Cloud Storage) instead of routing them through your Rails server.
Attach Images Efficiently: Use has_one_attached or has_many_attached for file associations in models.
Avoid Serving Files via Rails: Use a CDN or proxy service to serve images instead of relying on Rails controllers.
Clean Up Unused Blobs: Regularly remove orphaned blob records using ActiveStorage::Blob.unattached.destroy_all.
Optimize Image Processing: Use variants (image.variant(resize: "300x300").processed) to generate resized images efficiently.
In Rails 8, Active Storage uses two main tables for handling file uploads:
1. active_storage_blobs Table
This table stores metadata about the uploaded files but not the actual files. Each row represents a unique file (or “blob”) uploaded to Active Storage.
Columns in active_storage_blobs Table:
id – Unique identifier for the blob.
key – A unique key used to retrieve the file.
filename – The original name of the uploaded file.
content_type – The MIME type (e.g., image/jpeg, application/pdf).
metadata – JSON data storing additional information (e.g., width/height for images).
service_name – The storage service (e.g., local, amazon, google).
byte_size – File size in bytes.
checksum – A checksum to verify file integrity.
created_at – Timestamp when the file was uploaded.
👉 Purpose: This table allows a single file to be attached to multiple records without duplicating the file itself.
Why Does Rails Need Both Tables?
Separation of Concerns:
active_storage_blobstracks the files themselves.
active_storage_attachmentslinks them to models.
Efficient File Management:
The same file can be used in multiple places without storing it multiple times.
If a file is no longer attached to any record, Rails can remove it safely.
Supports Different Attachments:
A model can have different types of attachments (avatar, cover_photo, documents).
A single model can have multiple files attached (has_many_attached).
Example Usage in Rails 8
class User < ApplicationRecord
has_one_attached :avatar # Single file
has_many_attached :photos # Multiple files
end
When a file is uploaded, an entry is added to active_storage_blobs, and an association is created in active_storage_attachments.
How Rails Queries These Tables
user.avatar # Fetches from `active_storage_blobs` via `active_storage_attachments`
user.photos.each { |photo| puts photo.filename } # Fetches multiple attached files
Conclusion
Rails 8 uses two tables to decouple file storage from model associations, enabling better efficiency, flexibility, and reusability. This structure allows models to reference files without duplicating them, making Active Storage a powerful solution for file management in Rails applications. 🚀
Where Are Files Stored in Rails 8 by Default?
By default, Rails 8 stores uploaded files using Active Storage’s disk service, meaning files are saved in the storage/ directory within your Rails project.
Default Storage Location:
Files are stored in: storage/ ├── cache/ (temporary files) ├── store/ (permanent storage) └── variant/ (image transformations like resizing)
The exact file path inside storage/ is determined by the key column in the active_storage_blobs table. For example, if a blob entry has: key = 'xyz123abcd' then the file is stored at: storage/store/xyz123abcd
How to Change the Storage Location?
You can configure storage in config/storage.yml. For example:
local:
service: Disk
root: <%= Rails.root.join("storage") %>
# Use bin/rails credentials:edit to set the AWS secrets (as aws:access_key_id|secret_access_key)
amazon:
service: S3
access_key_id: <%= Rails.application.credentials.dig(:aws, :access_key_id) %>
secret_access_key: <%= Rails.application.credentials.dig(:aws, :secret_access_key) %>
region: us-east-1
bucket: your_own_bucket-<%= Rails.env %>
Then, update config/environments/development.rb (or production.rb) to use:
config.active_storage.service = :local # or :amazon for S3
How to Get the Stored File Path in Rails 8 Active Storage
Since Rails stores files in a structured directory inside storage/, the actual file path can be determined using the key stored in the active_storage_blobs table.
Get the File Path in Local Storage
If you’re using the Disk service (default for development and test), you can retrieve the stored file path manually:
Files are stored in the storage/ directory by default.
Use rails_blob_url or service_url to get an accessible URL.
Use variant to generate resized versions.
For production, it’s best to use a cloud storage service like Amazon S3.
Understanding has_one_attached and has_many_attached in Rails 8
Rails 8 provides a built-in way to handle file attachments through Active Storage. The key methods for attaching files to models are:
has_one_attached – For a single file attachment.
has_many_attached – For multiple file attachments.
Let’s break down what they do and why they are useful.
1. has_one_attached
This is used when a model should have a single file attachment. For example, a User model may have only one profile picture.
Usage:
class User < ApplicationRecord
has_one_attached :avatar
end
How It Works:
When you upload a file, Active Storage creates an entry in the active_storage_blobs table.
The active_storage_attachments table links this file to the record.
If a new file is attached, the old one is automatically replaced.
Example: Attaching and Displaying an Image
user = User.find(1)
user.avatar.attach(io: File.open("/path/to/avatar.jpg"), filename: "avatar.jpg", content_type: "image/jpeg")
# Checking if an avatar exists
user.avatar.attached? # => true
# Displaying the image in a view
<%= image_tag user.avatar.variant(resize: "100x100").processed if user.avatar.attached? %>
2. has_many_attached
Use this when a model can have multiple file attachments. For instance, a Product model may have multiple images.
Usage:
class Product < ApplicationRecord
has_many_attached :images
end
How It Works:
Multiple files can be attached to a single record.
Active Storage tracks all file uploads in the active_storage_blobs and active_storage_attachments tables.
Deleting an attachment removes it from storage.
Example: Attaching and Displaying Multiple Images
product = Product.find(1)
product.images.attach([
{ io: File.open("/path/to/image1.jpg"), filename: "image1.jpg", content_type: "image/jpeg" },
{ io: File.open("/path/to/image2.jpg"), filename: "image2.jpg", content_type: "image/jpeg" }
])
# Checking if images exist
product.images.attached? # => true
# Displaying all images in a view
<% if product.images.attached? %>
<% product.images.each do |image| %>
<%= image_tag image.variant(resize: "200x200").processed %>
<% end %>
<% end %>
Benefits of Using has_one_attached & has_many_attached
Simplifies File Attachments – Directly associates files with Active Record models.
No Need for Extra Tables – Unlike some gems (e.g., CarrierWave), Active Storage doesn’t require additional tables for storing file paths.
Easy Cloud Storage Integration – Works seamlessly with Amazon S3, Google Cloud Storage, and Azure.
Variant Processing – Generates resized versions of images using variant (e.g., thumbnails).
Automatic Cleanup – Old attachments are automatically removed when replaced.
Final Thoughts
Active Storage in Rails 8 provides a seamless way to manage file uploads, integrating directly with models while handling storage efficiently. By understanding how it processes uploads internally, we can better optimize performance and ensure a smooth user experience.
In an upcoming blog, we’ll dive deeper into Turbo Streams and how they enhance real-time updates in Rails applications.
Note: You can see this create a Procfile.dev file and installs foreman gem.
The foreman gem in Rails is used to manage and run multiple processes in development using a Procfile. It is particularly useful when your Rails application depends on several background services that need to run simultaneously.
Why is foreman used?
It allows you to define and manage multiple services (like Rails server, Tailwind compiler, Sidekiq, etc.) in a single command.
Ensures that all necessary processes start together, making development easier.
Helps simulate production environments where multiple services need to run concurrently.
Who is using foreman? Rails or Tailwind CSS?
The foreman gem itself is not specific to Rails or Tailwind CSS—it is a general-purpose process manager.
In our case, both Rails and Tailwind CSS are using foreman.
Rails: You can use foreman to start Rails server, background jobs, and Webpack.
Tailwind CSS: Since Tailwind needs a process to watch and compile CSS files (using npx tailwindcss -i input.css -o output.css --watch), foreman helps keep this process running.
What is Procfile.dev in Tailwind CSS?
When you install Tailwind in Rails, a Procfile.dev is created to define the processes required for development.
Example Procfile.dev for Tailwind and Rails: web: bin/rails server -p 3000 js: yarn build --watch css: bin/rails tailwindcss:watch
web: Starts the Rails server.
js: Watches and compiles JavaScript files (if using esbuild or webpack).
css: Watches and compiles Tailwind CSS files.
How to use foreman?
Run the following command to start all processes defined in Procfile.dev: bin/dev
This starts the Rails server, the Tailwind CSS watcher, and other necessary processes.
The foreman gem is used as a process manager to run multiple services in development. In our case, both Rails and Tailwind CSS are using it. It ensures that Tailwind’s CSS compilation process runs alongside the Rails server.
2. Use Tailwind Classes in Views
Example:
<div class="container mx-auto p-4">
<h1 class="text-blue-500 text-3xl font-bold">Welcome to My App</h1>
<button class="bg-green-500 text-white px-4 py-2 rounded">Click Me</button>
</div>
This keeps your CSS minimal, avoids custom stylesheets, and helps you learn Tailwind naturally while building your app.
Here’s a Tailwind CSS Cheat Sheet to help you get started quickly with your Rails 8 app.
In the first part of this guide, we covered setting up a Rails 8 app with essential configurations. In this follow-up, we’ll go over optimizing command-line usage, setting up VS Code for development, running migrations, styling the app, and enabling Action Text.
1. Optimizing Command-Line Usage with Aliases
One of the best ways to speed up development is to create shortcuts for frequently used commands. You can do this by adding aliases to your shell configuration.
Steps to Add an Alias:
Open your shell configuration file: vim ~/.zshrc
Search for the alias section: <esc> / alias <enter>
Add your alias: alias gs="git status"
Save and exit: <esc> :wq
Reload your configuration: source ~/.zshrc
Use your new alias: gs
This method saves time by allowing you to run frequently used commands more quickly.
2. Using Terminal Efficiently in VS Code
By default, VS Code uses `Ctrl + “ to toggle the terminal, which may not be intuitive. You can change this shortcut:
Open VS Code.
Go to Settings → Keyboard Shortcuts.
Search for Toggle Terminal.
Click Edit and change it to Ctrl + Opt + T for easier access.
3. Setting Up RuboCop in VS Code
RuboCop ensures your Ruby code follows best practices. Here’s how to set it up:
Checking RuboCop from the Terminal:
rubocop .
VS Code Setup:
Open Command Palette (Cmd + Shift + P) and search for “Lint by RuboCop”.
Go to Extensions Tab and install “VS Code RuboCop”.
In VS Code Settings, search for “Rubocop” and check Ruby -> Rubocop -> Execute Path.
Find the RuboCop installation path: whereis rubocop Example output: ~/.local/share/mise/installs/ruby/3.4.1/bin/rubocop/
Update the Execute Path in VS Code to: ~/.local/share/mise/installs/ruby/3.4.1/bin/
If RuboCop still returns an empty output, check .rubocop.yml in your project: ~/rails/design_studio/.rubocop.yml
If the issue persists, ensure the gem is installed: gem install rubocop
Restart VS Code from the Rails project root: code .
For more details, check the official documentation: RuboCop Usage
4. Running Migrations and Starting the Server
Running Migrations:
rails db:migrate -t
You can check the file: db/schema.rb You can see the active storage tables for attachments and other info.
Ruby on Rails 8 introduces several improvements that make development easier, more secure, and more maintainable. In this guide, we’ll walk through setting up a new Rails 8 application while noting the significant configurations and features that come out of the box.
Rails 8 provides new shortcuts and syntax improvements for database migrations:
NOT NULL Constraints with ! Shortcut
You can impose NOT NULL constraints directly from the command line using !:
# Example for not null constraints:
➜ rails generate model User name:string!
Type Modifiers in Migrations
Rails 8 allows passing commonly used type modifiers directly via the command line. These modifiers are enclosed in curly braces {} after the field type.
# Example for model generation:
➜ rails generate model Product name:string description:text
# Example for passing modifiers:
➜ rails generate migration AddDetailsToProducts 'price:decimal{5,2}' supplier:references{polymorphic}
Generating a Scaffold for the Product Model
Let’s generate a complete scaffold for our Product model:
The rails g resource command is a powerful way to generate models, controllers, migrations, and routes all in one go. This is particularly useful when setting up RESTful resources in a Rails application.
Basic Syntax
➜ rails g resource product
This command creates the necessary files for a new resource, including:
A model (app/models/product.rb)
A migration file (db/migrate/)
A controller (app/controllers/product_controller.rb)
Routes in config/routes.rb
A test file (test/controllers/product_controller_test.rb or spec/)
Example Usage
To generate a Post resource with attributes:
➜ rails g resource Product title:string! description:text brand:references
This will:
Create a Product model with title and description attributes.
Add a brand_id foreign key as a reference.
Apply a NOT NULL constraint on title (! shortcut).
Generate a corresponding migration file.
Set up routes automatically (resources :products).
Running the Migration
After generating a resource, apply the migration to update the database:
➜ rails db:migrate
Difference Between resource and scaffold
Rails provides both rails g resource and rails g scaffold, but they serve different purposes:
Feature
rails g resource
rails g scaffold
Generates a Model
✅
✅
Generates a Migration
✅
✅
Generates a Controller
✅ (empty actions)
✅ (full CRUD actions)
Generates Views (HTML/ERB)
❌
✅ (index, show, new, edit, etc.)
Generates Routes
✅
✅
Generates Helper Files
❌
✅
Generates Tests
✅
✅
rails g resource is minimal—it generates only essential files without view templates. It’s useful when you want more control over how your views and controller actions are built.
rails g scaffold is more opinionated and generates full CRUD functionality with prebuilt forms and views, making it ideal for rapid prototyping.
If you need full CRUD functionality quickly, use scaffold. If you prefer a leaner setup with manual control over implementation, use resource.
Conclusion
Rails 8 significantly enhances the development experience with built-in security tools, CI/CD workflows, streamlined deployment via Kamal, and modern front-end support with Turbo & Stimulus. It also improves caching, background jobs, and real-time features with Solid tools.
These improvements make Rails 8 a robust framework for modern web applications, reducing the need for additional dependencies while keeping development efficient and secure.
Ruby is known for its elegant and expressive syntax, making it one of the most enjoyable programming languages to work with. In this blog post, we will explore some interesting aspects of Ruby, including syntax sugar, operator methods, useful array operations, and handy built-in methods.
Ruby Syntax Sugar
Ruby provides several shorthand notations that enhance code readability and reduce verbosity. Let’s explore some useful syntax sugar techniques.
Shorthand for Array and Symbol Arrays
Instead of manually writing arrays of strings or symbols, Ruby provides %w and %i shortcuts.
words = %w[one two three] # => ["one", "two", "three"]
symbols = %i[one two three] # => [:one, :two, :three]
Many mathematical and array operations in Ruby are actually method calls, thanks to Ruby’s message-passing model.
puts 1.+(2) # => 3 (Same as 1 + 2)
Array Indexing and Append Operations
words = %w[zero one two three four]
puts words.[](2) # => "two" (Equivalent to words[2])
words.<<('five') # => ["zero", "one", "two", "three", "four", "five"] (Equivalent to words << "five")
Avoiding Dot Notation with Operators
# Bad practice
num = 10
puts num.+(5) # Avoid this syntax
# Good practice
puts num + 5 # Preferred
Using a linter like rubocop can help enforce best practices in Ruby code.
none? Method in Ruby Arrays
The none? method checks if none of the elements in an array satisfy a given condition.
numbers = [1, 2, 3, 4, 5]
puts numbers.none? { |n| n > 10 } # => true (None are greater than 10)
puts numbers.none?(&:odd?) # => false (Some numbers are odd)
This method is useful for quickly asserting that an array does not contain specific values.
Exponent Operator (**) and XOR Operator (^)
Exponentiation
Ruby uses ** for exponentiation instead of ^ (which performs a bitwise XOR operation).
puts 2 ** 3 # => 8 (2 raised to the power of 3)
puts 10 ** 0.5 # => 3.162277660168379 (Square root of 10)
XOR Operator
In Ruby, ^ is used for bitwise XOR operations, which differ from exponentiation.
This is particularly useful for cleaning up user input or text from external sources.
Conclusion
Ruby’s syntax sugar, operator methods, and built-in methods make code more readable, expressive, and powerful. By leveraging these features effectively, you can write clean, efficient, and maintainable Ruby code.
Ruby is an elegant and expressive language that stands out due to its simplicity and readability. While its syntax is designed to be natural and easy to use, Ruby also has several powerful and unique features that make it a joy to work with. Let’s explore some of the fascinating aspects of Ruby that set it apart from other programming languages.
Everything is an Expression
Unlike many other languages where statements exist separately from expressions, in Ruby, everything is an expression. Every line of code evaluates to something, even function definitions. For example:
result = def greet
"Hello, World!"
end
puts result # => :greet
Here, defining the greet method itself returns a symbol representing its name, :greet. This feature makes metaprogramming and introspection very powerful in Ruby.
Other examples:
Conditional expressions return values:
value = if 10 > 5
"Greater"
else
"Smaller"
end
puts value # => "Greater"
Loops also evaluate to a return value:
result = while false
"This won't run"
end
puts result # => nil
result = until true
"This won't run either"
end
puts result # => nil
Assignment is an expression:
x = y = 10 + 5
puts x # => 15
puts y # => 15
Case expressions return values:
day = "Sunday"
message = case day
when "Monday"
"Start of the week"
when "Friday"
"Almost weekend!"
when "Sunday"
"Time to relax!"
else
"Just another day"
end
puts message # => "Time to relax!"
This characteristic of Ruby allows concise and elegant code that minimizes the need for temporary variables and makes code more readable.
The send Method for Dynamic Method Invocation
While Ruby does not allow storing functions in variables (like JavaScript or Python), you can hold their identifiers as symbols and invoke them dynamically using send:
Why does Ruby use .send instead of .call? The call method is used for Proc and lambda objects, whereas send is a general method that allows invoking methods dynamically on an object. This also enables calling private methods.
So the question is can we restrict the programmer calling private methods with send? Let’s look at some examples how we can do that.
1. Use public_send Instead of send
The public_send method only allows calling public methods, preventing invocation of private methods.
class Demo
private
def secret_method
"This is private!"
end
end
d = Demo.new
puts d.public_send(:secret_method) # Raises NoMethodError
2. Override send in Your Class
You can override send in your class to restrict private method access.
class SecureDemo
def send(method, *args)
if private_methods.include?(method)
raise NoMethodError, "Attempt to call private method `#{method}`"
else
super
end
end
private
def secret_method
"This is private!"
end
end
d = SecureDemo.new
puts d.send(:secret_method) # Raises NoMethodError
Use private_method_defined? to Manually Check for Access Level
Before calling a method via send, verify if it is public.
class SecureDemo
def send(method, *args)
if self.class.private_method_defined?(method)
raise NoMethodError, "private method `#{method}` called"
else
super
end
end
private
def secret_method
"This is private!"
end
end
d = SecureDemo.new
puts d.send(:secret_method) # Raises NoMethodError
Why private_method_defined? Instead of method_defined??
method_defined? checks for public and protected methods but ignores private ones.
private_method_defined? explicitly checks for private methods, which is what we need here.
This ensures only public methods are called dynamically.
puts, p, and print – What’s the Difference?
Ruby provides multiple ways to output text:
puts calls .to_s on its argument and prints it, followed by a newline, but always returns nil.
p prints the argument using .inspect, preserving its original representation and also returns the argument.
Using a linter and following a style guide ensures consistency and readability. Tools like RuboCop help enforce best practices.
These features showcase Ruby’s power and expressiveness. With its readable syntax, metaprogramming capabilities, and intuitive design, Ruby remains a top choice for developers who value simplicity and elegance in their code.
Rails 8.x has arrived, bringing exciting new features and enhancements to improve productivity, performance, and ease of development. From built-in authentication to real-time WebSocket updates, this latest version of Rails continues its commitment to being a powerful and developer-friendly framework.
Let’s dive into some of the most significant features and improvements introduced in Rails 8.
Rails 8 Features & Enhancements
1. Modern JavaScript with Importmaps & Hotwire
Rails 8 eliminates the need for Webpack and Node.js, allowing developers to manage JavaScript dependencies more efficiently. Importmaps simplify dependency management by fetching JavaScript packages directly and caching them locally, removing runtime dependencies.
Key Benefits:
Faster page loads and reduced complexity
No need for Node.js or Webpack
Dependencies are cached locally and loaded efficiently
Example: Pinning a Package
bin/importmap pin local-time
This command fetches the package from npm and stores it locally for future use.
Hotwire Integration
Hotwire enables dynamic page updates without requiring heavy JavaScript frameworks. Rails 8 fully integrates Turbo and Stimulus, making frontend interactivity more seamless.
Importing Dependencies in application.js:
import "trix";
With this setup, developers can create reactive UI elements with minimal JavaScript.
2. Real-Time WebSockets with Action Cable & Turbo Streams
Rails 8 enhances real-time functionality with Action Cable and Turbo Streams, allowing WebSocket-based updates across multiple pages without additional JavaScript libraries.
Setting Up Turbo Streams in Views:
<%= turbo_stream_from @object %>
This creates a WebSocket channel tied to the object.
Any changes to the object will be instantly reflected across all connected clients.
Why This Matters:
No need for third-party WebSocket npm packages
Real-time updates are built into Rails
Simplifies building interactive applications
3. Rich Text with ActionText
Rails 8 continues to support ActionText, making it easy to handle rich text content within models and views.
Model Level Implementation:
has_rich_text :body
This enables rich text storage and formatting for the body attribute of a model.
View Implementation:
<%= form.rich_text_area :body %>
This adds a full-featured WYSIWYG text editor to the form, allowing users to create and edit rich text content seamlessly.
Displaying Updated Timestamps:
<%= time_tag post.updated_at %>
This helper formats timestamps cleanly, improving date and time representation in views.
4. Deployment with Kamal – Simpler & Faster
Rails 8 introduces Kamal, a modern deployment tool that simplifies remote deployment by leveraging Docker containers.
Deployment Steps:
Setup Remote Serverkamal setup
Installs Docker (if missing) and configures the server.
Deploy the Applicationkamal deploy
Builds and ships a Docker container using Rails’ default Dockerfile.
File Uploads with Active Storage
By default, Kamal stores uploaded files in Docker volumes, but this can be customized based on specific deployment needs.
5. Built-in Authentication – No Devise Needed
Rails 8 introduces native authentication, reducing reliance on third-party gems like Devise. This built-in system manages password encryption, user sessions, and password resets while keeping signup flows flexible.
Ensure manifest and service-worker routes are enabled.
Verify PWA files: pwa/manifest.json.erb and pwa/service-worker.js.
Deploy and restart the application to see the Install button in the browser.
Final Thoughts
Rails 8 is packed with developer-friendly features that improve security, real-time updates, and deployment workflows. With Hotwire, Kamal, and native authentication, it’s clear that Rails is evolving to reduce dependencies while enhancing performance.
Are you excited about Rails 8? Let me know your thoughts and experiences in the comments below!
Ruby is a dynamically typed language that favors duck typing over strict type enforcement. However, there are cases where type checking can be useful to avoid unexpected behavior. In this post, we’ll explore various ways to perform type validation and type checking in Ruby.
Type Checking and Type Casting in Ruby
Yes, even though Ruby does not enforce types at the language level, there are several techniques to validate the types of method parameters. Below are some approaches:
1. Manual Type Checking with raise
One straightforward way to enforce type checks is by manually verifying the type of a parameter using is_a? and raising an error if it does not match the expected type.
def my_method(arg)
raise TypeError, "Expected String, got #{arg.class}" unless arg.is_a?(String)
puts "Valid input: #{arg}"
end
my_method("Hello") # Works fine
my_method(123) # Raises: TypeError: Expected String, got Integer
2. Using respond_to? for Duck Typing
Rather than enforcing a strict class type, we can check whether an object responds to a specific method.
def my_method(arg)
unless arg.respond_to?(:to_str)
raise TypeError, "Expected a string-like object, got #{arg.class}"
end
puts "Valid input: #{arg}"
end
my_method("Hello") # Works fine
my_method(:symbol) # Raises TypeError
3. Using Ruby 3’s Type Signatures (RBS)
Ruby 3 introduced RBS and TypeProf for static type checking. You can define types in an .rbs file:
def my_method: (String) -> void
Then, you can use tools like steep, a static type checker for Ruby, to enforce type checking at development time.
How to Use Steep for Type Checking
Steep does not use annotations or perform type inference on its own. Instead, it relies on .rbi files to define type signatures. Here’s how you can use Steep for type checking:
Define a Ruby Class:
class Calculator
def initialize(value)
@value = value
end
def double
@value * 2
end
end
Generate an .rbi File:
steep scaffold calculator.rb > sig/calculator.rbi
This generates an .rbi file, but initially, it will use any for all types. You need to manually edit it to specify proper types.
Modify the .rbi File to Define Types:
class Calculator
@value: Integer
def initialize: (Integer) -> void
def double: () -> Integer
end
Run Steep to Check Types:
steep check
Steep also supports generics and union types, making it a powerful but less intrusive type-checking tool compared to Sorbet.
4. Using Sorbet for Stronger Type Checking
Sorbet is a third-party static type checker that allows you to enforce type constraints at runtime.
require 'sorbet-runtime'
extend T::Sig
sig { params(arg: String).void }
def my_method(arg)
puts "Valid input: #{arg}"
end
my_method("Hello") # Works fine
my_method(123) # Raises error at runtime
Another Approach: Using Rescue for Type Validation
A different way to handle type checking is by using exception handling (rescue) to catch unexpected types and enforce validation.
def process_order(order_items, customer_name, discount_code)
# Main logic
...
rescue => e
# Type and validation checks
raise "Expecting an array of items: #{order_items.inspect}" unless order_items.is_a?(Array)
raise "Order must contain at least one item: #{order_items.inspect}" if order_items.empty?
raise "Expecting a string for customer name: #{customer_name.inspect}" unless customer_name.is_a?(String)
raise "Customer name cannot be empty" if customer_name.strip.empty?
raise "Unexpected error in `process_order`: #{e.message}"
end
Summary
Use is_a? or respond_to? for runtime type checking.
Use Ruby 3’s RBS for static type enforcement.
Use Sorbet for stricter type checking at runtime.
Use Steep for static type checking with RBS.
Exception handling can be used for validating types dynamically.
Additional Considerations
Ruby is a dynamically typed language, and unit tests can often be more effective than type checks in ensuring correctness. Writing tests ensures that method contracts are upheld for expected data.
For Ruby versions prior to 3.0, install the rbs gem separately to define types for classes.
If a method is defined, it will likely be called. If reasonable tests exist, every method will be executed and checked. Therefore, instead of adding excessive type checks, investing time in writing tests can be a better strategy.