Ruby On Rails Unique Methods
π 25 Unique Ruby on Rails Methods You Need to Know! β¨
Ruby on Rails is renowned for its elegance and simplicity, providing developers with powerful tools and methods to build applications quickly and efficiently. While some methods are commonly known, Rails also packs a bunch of unique and lesser-known gems that can save you hours of work! Letβs dive into 25 unique Ruby on Rails methods every developer should know, complete with explanations and examples. π οΈ
1. present?
and blank?
π€
Determine if an object is present or empty. These are much smarter than nil?
and work for strings, arrays, hashes, and more.
name = "Ruby on Rails"
puts name.present? # true
puts "".blank? # true
2. squish
π§Ή
Removes all leading, trailing, and excessive inner whitespace from a string. Perfect for cleaning up messy input!
messy_string = " Too much space! "
puts messy_string.squish # "Too much space!"
3. pluck
π±
Fetch specific fields directly from the database without loading full objects. Itβs a game-changer for performance optimization.
User.pluck(:name) # ["Alice", "Bob", "Charlie"]
4. in_groups_of
π¦
Split an array into groups of a specified size. Handy for pagination or displaying items in a grid.
[1, 2, 3, 4, 5, 6].in_groups_of(2) # [[1, 2], [3, 4], [5, 6]]
5. where.not
π«
Exclude records from a query. Simplifies writing complex queries!
User.where.not(admin: true) # All non-admin users
6. try
π‘οΈ
Call a method on an object if it exists, avoiding NoMethodError
.
user = nil
puts user.try(:name) # nil (no error!)
7. deep_merge
π
Merge two hashes recursively. Perfect for configurations or nested data structures.
hash1 = { a: { b: 1 } }
hash2 = { a: { c: 2 } }
puts hash1.deep_merge(hash2) # { a: { b: 1, c: 2 } }
8. time_ago_in_words
β³
Convert a timestamp into a human-readable relative time. Great for activity feeds!
time = 5.minutes.ago
puts time_ago_in_words(time) # "5 minutes ago"
9. compact
ποΈ
Remove nil
values from an array or hash effortlessly.
[1, nil, 2, nil, 3].compact # [1, 2, 3]
10. enum
ποΈ
Define enumerable values for a field. Itβs cleaner and more semantic than using plain integers.
class Post < ApplicationRecord
enum status: { draft: 0, published: 1 }
end
Post.published # All published posts
11. to_sentence
ποΈ
Format an array into a human-readable sentence.
["Alice", "Bob", "Charlie"].to_sentence # "Alice, Bob, and Charlie"
12. find_each
π
Efficiently iterate over large ActiveRecord collections in batches to avoid memory issues.
User.find_each(batch_size: 100) { |user| puts user.name }
13. before_action
π―
Execute specific logic before a controller action. A Rails classic!
class UsersController < ApplicationController
before_action :set_user, only: [:show, :edit]
def set_user
@user = User.find(params[:id])
end
end
14. safe_constantize
π‘οΈ
Convert a string to a constant safely.
"User".safe_constantize # User
"InvalidClass".safe_constantize # nil (no error!)
15. as_json
π
Customize how objects are converted to JSON.
class User < ApplicationRecord
def as_json(options = {})
super(only: [:id, :name])
end
end
16. content_tag
π·οΈ
Dynamically create HTML tags in your views.
content_tag(:div, "Hello World!", class: "greeting")
# <div class="greeting">Hello World!</div>
17. reverse_merge
π
Merge a hash with defaults only if keys are missing.
options = { a: 1 }.reverse_merge(b: 2) # { a: 1, b: 2 }
18. find_or_create_by
β¨
Find or create a record in one go.
User.find_or_create_by(email: "test@example.com")
19. truncate
βοΈ
Truncate a string to a specified length, perfect for summaries or previews.
"Ruby on Rails is amazing!".truncate(10) # "Ruby on..."
20. uniq
π
Remove duplicate elements from an array.
[1, 2, 2, 3].uniq # [1, 2, 3]
21. alias_attribute
πͺ
Create a new name for an existing attribute.
class User < ApplicationRecord
alias_attribute :full_name, :name
end
22. cache
β‘
Use caching in views for performance.
<% cache @user do %>
<%= @user.name %>
<% end %>
23. helper_method
π οΈ
Make a controller method accessible in views.
class ApplicationController < ActionController::Base
helper_method :current_user
def current_user
@current_user ||= User.find(session[:user_id])
end
end
24. sanitize
π§Ό
Clean input to prevent XSS attacks.
sanitize("<script>alert('hacked!')</script>") # ""
25. reload
π
Reload an object from the database.
user = User.find(1)
user.reload # Refresh the user record
π Conclusion
These 25 unique methods are just a glimpse of the power Rails puts at your fingertips. Mastering them will not only make you a faster developer but also a smarter one! π‘
So, which method are you adding to your toolkit today? Let us know in the comments! π
© Lakhveer Singh Rajput - Blogs. All Rights Reserved.