# What are macros?
353
In Ruby on Rails, macros are methods that generate other methods or code. They are often used to define associations, validations, and other behaviors in a declarative way. Macros help in writing cleaner and more readable code by abstracting repetitive tasks.
Common Macros in Rails
Associations: Macros like has_many, belongs_to, and has_one are used to define relationships between models.
class User < ApplicationRecord has_many :posts belongs_to :account end
Validations: Macros like validates are used to ensure data integrity.
class User < ApplicationRecord
validates :email, presence: true, uniqueness: true
end
Callbacks: Macros like before_save, after_create, etc., are used to define callbacks.
class User < ApplicationRecord before_save :normalize_name private def normalize_name self.name = name.downcase.titleize end end
How Macros Work
Macros are essentially class-level methods that define behaviour for instances of the class. When you use a macro, it dynamically generates methods and other code that gets executed when the class is loaded.
Example:
class User < ApplicationRecord has_many :posts end
The has_many :posts macro generates methods like posts, posts.build, and posts.create for the User class, allowing you to interact with associated Post objects easily.
Creating Custom Macros
You can also create your own macros in Rails. Here’s a simple example of a custom macro that adds a class method to log messages:
module Loggable def log_message(message) define_method(:log) do puts message end end end class ApplicationRecord < ActiveRecord::Base extend Loggable end class User < ApplicationRecord log_message "User created!" end user = User.new user.log # Output: User created!
Macros in Rails make it easier to write DRY (Don’t Repeat Yourself) code by encapsulating common patterns and behaviours into reusable methods.