Ruby
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Methods and Blocks
-
Section 4: Object-Oriented Ruby
-
Section 5: Metaprogramming
-
Section 6: Working with Data and Files
-
Section 7: Ruby Frameworks Overview
-
Section 8: Ecosystem and Testing
-
Section 9: Practical Projects
-
Section 10: Interview Practice
-
Section 11: Data Structures and Algorithms in Ruby
-
Section 12: More Practice Exercises
-
Section 13: Enumerable and Functional Style
-
Section 14: More OOP Practice
-
Section 15: More Testing
-
Section 16: Enumerable and Comparable Modules In Depth
-
Section 17: Ruby Standard Library: Core Utilities
-
Section 18: Ruby Standard Library: Data and Security
-
Section 19: Ruby Standard Library: CLI and Text
-
Section 20: Ruby Networking
-
Section 21: Ruby on Rails Deep Dive
-
Section 22: Ruby Metaprogramming Deep Dive
-
Section 23: Ruby Design Patterns
-
Section 24: Ruby Concurrency
-
Section 25: Ruby Testing Deep Dive
-
Section 26: Ruby Gems and Packaging
-
Section 27: Ruby Performance
-
Section 28: More Practice Exercises
-
Section 29: More Interview Practice
-
Section 30: Rails API Development
-
Section 31: Rails Authentication and Authorization
-
Section 32: Rails Testing Deep Dive
-
Section 33: Rails Performance
-
Section 34: Rails Deployment
-
Section 35: Sinatra and Lightweight Ruby Web Apps
-
Section 36: More Ruby Language Deep Dive
-
Section 37: Ruby 3.x Modern Features
-
Section 38: More Data Structures in Ruby
-
Section 39: More Practical Projects
-
Section 40: Ruby Ecosystem Tools
-
Section 41: More Practice and Review
-
Section 42: Final Practice and Mastery
-
Section 43: Ruby Interview Deep Dive
-
Section 44: Ruby Background Processing Deep Dive
-
Section 45: Ruby GraphQL
-
Section 46: Ruby Object Model Deep Dive
-
Section 47: Ruby Hanami Framework Overview
-
Section 48: Ruby gRPC and Protocol Buffers
-
Section 49: Ruby Data Processing
-
Section 50: Ruby Search Integration
-
Section 51: Ruby File Upload and Media
-
Section 52: Ruby Email and Notifications
-
Section 53: Ruby Admin Panels
-
Section 54: Ruby Feature Flags and Experimentation
-
Section 55: Ruby Monitoring and Observability
-
Section 56: Ruby Docker and Deployment Deep Dive
-
Section 57: Ruby Security Deep Dive
-
Section 58: More Advanced Metaprogramming
-
Section 59: More Final Projects
242: Class Macros Like has_many Explained
If you've spent any time with Ruby on Rails, you've seen lines like has_many :comments or validates :email, presence: true. They look like special keywords or configuration settings, but they aren't. They are just Ruby methods. We call them "class macros" because they change the structure of the class while it's being defined.
I remember a junior dev on my team trying to build a lightweight custom validation system for a non-Rails project. They wrote this, and they were genuinely baffled when it crashed immediately on startup:
class User
def validates(field)
puts "Validating #{field}..."
end
validates :username
end
# Result: NoMethodError (undefined method `validates' for User:Class)
The NoMethodError Mystery
At first glance, the code looks perfect. The method validates is defined right there in the class, and then it's called. But here is the thing about Ruby: the code inside a class definition (but outside of any method) is executed immediately as the class is being loaded.
When Ruby hits the line validates :username, it is executing that call in the context of the User class object itself, not an instance of User. However, the validates method was defined as an instance method. You can't call an instance method on the class object. It's like trying to drive a car by sitting on the roof; you're in the right general area, but you're not in the driver's seat.
Elevating the Method to the Class Level
To fix this, we need to make validates a class method. By adding self. to the method definition, we tell Ruby that this method belongs to the class object, making it available to be called during the class definition phase.
class User
def self.validates(field)
puts "Validating #{field}..."
end
validates :username
end
# This now works!
# Output: Validating username...
Now the code runs, but it's still not very useful. All it does is print a string. A real class macro doesn't just "do something" once; it usually "sets something up" for the instances of that class to use later.
How the Magic Actually Works
The "magic" of has_many or validates is that these methods use metaprogramming to define other methods on the fly. I like to think of a class macro as a method that writes more methods.
Let's turn our validates macro into something that actually works. We'll have it create a validation method for every field we specify:
class User
def self.validates(field)
# We are defining a new instance method on the fly
define_method("validate_#{field}?") do
puts "Checking if #{field} is present..."
!self.send(field).nil?
end
end
attr_accessor :username, :email
validates :username
validates :email
end
user = User.new
user.username = "ruby_dev"
puts user.validate_username? # => Checking if username is present... true
puts user.validate_email? # => Checking if email is present... false
Here is what's happening under the hood:
- We call the class method
validates. - Inside that method, we use
define_method. This is a powerful Ruby tool that creates a new instance method based on the string or symbol we provide. - Because
define_methodis called within the context of theUserclass, the new method (e.g.,validate_username?) becomes available to every instance ofUser.
It’s a bit of a brain-bender the first time you see it. You're essentially using a method to manufacture other methods. This is exactly how Rails manages to keep its models so concise—it hides the repetitive boilerplate inside these macros.
📋 Practical Task
Build a Custom Relationship Macro
Your task is to implement a simple has_attribute class macro. Instead of manually writing getter and setter methods for a set of configuration options, you will create a macro that handles it for you.
Requirements:
- Create a class called
Setting. - Implement a class method
self.has_attribute(name). - The
has_attributemethod should usedefine_methodto create a getter method (e.g., if you callhas_attribute :theme, it should create a methodthemethat returns the value from an internal hash). - The
has_attributemethod should also create a setter method (e.g.,theme=`) that updates the value in that internal hash. - Initialize an empty hash called
@attributesin theinitializemethod of theSettingclass to store these values.
Example Usage:
class Setting
# Your macro implementation here
end
Setting.has_attribute :font_size
Setting.has_attribute :dark_mode
s = Setting.new
s.font_size = 12
puts s.font_size # Should print 12
There are no comments for now.