Ruby on Rails Predefined Classes
๐ Ruby on Rails Predefined Classes That Will Surprise Every Developer ๐ฒ๐ฅ
Ruby on Rails is not just about controllers, models, and viewsโฆ it comes packed with powerful predefined classes that can make your code cleaner, faster, and way more expressive ๐ก
Most developers barely scratch the surface โ but today, weโll dive deep into hidden gems ๐ of Rails classes that can transform your coding style into PRO level โก
๐ง 1. ActiveSupport::Concern โ Clean Modules Like a Pro
๐ก Why itโs powerful:
Managing modules with dependencies can get messy. ActiveSupport::Concern solves it elegantly.
๐ฅ Features:
- Automatically handles dependencies
- Cleaner inclusion syntax
- Supports
includedandclass_methodsblocks
๐งช Example:
module Trackable
extend ActiveSupport::Concern
included do
before_save :track_activity
end
def track_activity
puts "Tracking activity..."
end
class_methods do
def tracking_enabled?
true
end
end
end
๐ Now include it anywhere:
class User < ApplicationRecord
include Trackable
end
๐ฅ Pro Tip: Avoid plain Ruby modules when dealing with callbacks or dependencies.
โก 2. ActiveSupport::Inflector โ Magic with Strings
๐ก Why itโs powerful:
Handles pluralization, singularization, camelizationโฆ basically string transformation magic โจ
๐ฅ Features:
- Convert between naming conventions
- Handles irregular words
- Used internally by Rails
๐งช Example:
ActiveSupport::Inflector.pluralize("person") # => "people"
ActiveSupport::Inflector.camelize("user_name") # => "UserName"
ActiveSupport::Inflector.underscore("UserName") # => "user_name"
๐ฅ Hack: Create dynamic class names from strings!
โณ 3. ActiveSupport::Duration โ Human-Friendly Time
๐ก Why itโs powerful:
Write time logic like English sentences ๐ฃ๏ธ
๐ฅ Features:
- Chainable time helpers
- Works with
TimeandDate - Easy arithmetic
๐งช Example:
5.days.from_now
2.weeks.ago
1.year + 3.months
๐ฅ Real Use Case:
user.subscription_expires_at = 1.month.from_now
๐ฆ 4. ActiveSupport::HashWithIndifferentAccess โ Symbol or String? No Problem!
๐ก Why itโs powerful:
Access hash keys using string OR symbol ๐
๐ฅ Features:
- Eliminates key mismatch bugs
- Used in params hash
๐งช Example:
hash = ActiveSupport::HashWithIndifferentAccess.new
hash[:name] = "Lakhveer"
hash["name"] # => "Lakhveer"
hash[:name] # => "Lakhveer"
๐ฅ Pro Tip: Perfect for APIs & params handling.
๐งฌ 5. ActiveSupport::Callbacks โ Build Your Own Callbacks
๐ก Why itโs powerful:
Create callback systems like Rails models ๐คฏ
๐ฅ Features:
- Define custom callbacks
- Run before/after hooks
- Highly flexible
๐งช Example:
class Task
include ActiveSupport::Callbacks
define_callbacks :execute
def run
run_callbacks :execute do
puts "Executing task..."
end
end
end
๐ฅ Hack: Build your own mini Rails-like lifecycle system.
๐ ๏ธ 6. ActiveSupport::Configurable โ Config Like Rails
๐ก Why itโs powerful:
Create configurable classes just like Rails apps โ๏ธ
๐ฅ Features:
- Global configuration
- Easy setup for libraries
๐งช Example:
class AppConfig
include ActiveSupport::Configurable
end
AppConfig.configure do |config|
config.api_key = "12345"
end
AppConfig.config.api_key # => "12345"
๐ฅ Use Case: Build your own gems with configuration support.
๐งฉ 7. ActiveSupport::Delegation โ Delegate Like Magic
๐ก Why itโs powerful:
Avoid repetitive code by delegating methods ๐ฏ
๐ฅ Features:
- Cleaner code
- Less boilerplate
- Improves readability
๐งช Example:
class User
attr_accessor :profile
delegate :name, :age, to: :profile
end
๐ฅ Now:
user.name # instead of user.profile.name
๐ 8. ActiveSupport::MessageEncryptor โ Secure Your Data
๐ก Why itโs powerful:
Encrypt and decrypt sensitive data ๐
๐ฅ Features:
- Built-in encryption
- Secure key handling
- Used in cookies & sessions
๐งช Example:
crypt = ActiveSupport::MessageEncryptor.new(Rails.application.secret_key_base.byteslice(0..31))
encrypted = crypt.encrypt_and_sign("secret")
crypt.decrypt_and_verify(encrypted) # => "secret"
๐ฅ Real Use: Secure tokens, API secrets, cookies.
๐งฎ 9. ActiveSupport::NumberHelper โ Format Numbers Beautifully
๐ก Why itโs powerful:
Format numbers like currency, percentages ๐ฐ
๐งช Example:
include ActiveSupport::NumberHelper
number_to_currency(1000) # => "$1,000.00"
number_to_percentage(50) # => "50.000%"
๐ฅ Use Case: Dashboards, reports, UI display.
๐งต 10. ActiveSupport::TaggedLogging โ Smart Logging
๐ก Why itโs powerful:
Add tags to logs for better debugging ๐ต๏ธ
๐งช Example:
logger = ActiveSupport::TaggedLogging.new(Logger.new(STDOUT))
logger.tagged("USER") do
logger.info "User logged in"
end
๐ฅ Output:
[USER] User logged in
๐ฏ Final Thoughts
Rails is not just a frameworkโฆ itโs a toolkit full of hidden superpowers ๐ฅ
๐ Mastering these predefined classes will: โ Reduce boilerplate code โ Improve readability โ Make you a 10x Rails developer ๐
๐ง Must-Do Habits for Pro Developers
โ
Explore ActiveSupport regularly
โ
Read Rails source code ๐
โ
Refactor code using built-in helpers
โ
Avoid reinventing the wheel
โ ๏ธ Mistakes to Avoid
โ Ignoring built-in classes โ Writing custom logic for existing features โ Overcomplicating simple tasks โ Not leveraging Rails magic
๐ฌ Final Line
๐ฅ โRails doesnโt just give you toolsโฆ it gives you shortcuts to mastery.โ
© Lakhveer Singh Rajput - Blogs. All Rights Reserved.