๐Ÿš€ 25 Unique Ruby on Rails Methods You Need to Know! ✨

 


๐Ÿš€ 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! ๐Ÿš€


Comments

Popular posts from this blog

๐Ÿš€ Ruby on Rails 8: The Ultimate Upgrade for Modern Developers! Game-Changing Features Explained ๐ŸŽ‰๐Ÿ’Ž

๐Ÿš€ Uploading Large Files in Ruby on Rails: A Complete Guide

๐Ÿš€ Mastering Deployment: Top Tools You Must Know Before Launching Your App or Model!