Improve your Rails code readability with these three useful features.
Eliminate repetition with with_options
In Ruby, the with_options
method can be used to factor out duplicate options passed to a series of method calls.
The method takes a hash of options as its argument. Each method called in the block, with the block variable as the receiver, will have its options merged with the default options hash provided.
Instead of this:
1
2
3
4
5
class User < ApplicationRecord
validates :name, presence: true
validates :email, presence: true
validates :password, length: { minimum: 6 }
end
Use this:
1
2
3
4
5
6
7
class User < ApplicationRecord
with_options presence: true do
validates :name
validates :email
validates :password, length: { minimum: 6 }
end
end
Use the try
method to avoid errors and simplify your Ruby code
The try
method is a powerful tool that can be used to avoid runtime errors and simplify your code. The method works by trying to execute an expression and returning the result if the expression is successful, or nil
if the expression fails.
Instead of this:
1
2
3
4
5
user = User.find(1)
name = user.name if user
if name.nil?
puts "User not found"
end
Use this:
1
2
3
4
5
user = User.find(1)
name = try { user.name }
if name.nil?
puts "User not found"
end
The try
method can also be used to call a method that can throw an exception.
Instead of this:
1
2
3
4
5
6
file = File.open("file.txt")
begin
file.read
rescue => e
puts "Error reading file: #{e}"
end
Use this:
1
2
3
4
5
file = File.open("file.txt")
try { file.read }
rescue => e
puts "Error reading file: #{e}"
end
Using draw
to organize your Rails routes
The draw
feature can be used to organize your routes. By using draw
, you can group your routes into separate files, making your application code more readable and maintainable.
There are many ways to use draw
to organize your routes.
- By functionality: group routes by functionality, such as API routes, web routes, or admin routes.
- By model: group routes by model, such as routes for users, articles, or products.
- By domain: group routes by domain, such as routes for the www domain or the api domain.
Instead of this:
1
2
3
4
5
6
7
8
9
10
11
Rails.application.routes.draw do
# API routes
resources :users, only: [:index, :show, :create, :update, :destroy]
resources :articles, only: [:index, :show, :create, :update, :destroy]
# Web routes
get '/home', to: 'pages#home'
# Admin routes
get '/users', to: 'users#index'
end
Use this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# config/routes.rb
Rails.application.routes.draw do
draw 'api'
draw 'web'
draw 'admin'
end
# api.rb
Rails.application.routes.draw do
resources :users
resources :articles
end
# web.rb
Rails.application.routes.draw do
get '/home', to: 'pages#home'
end
# admin.rb
Rails.application.routes.draw do
get '/users', to: 'users#index'
end