What is a macro in Rails?

Viewed 4729

I was reading the Rails docs, and I have encountered the term macros. I can't find the definition of the term (in the context of Rails). Can someone point me to a place where the term is defined?

I am familiar with the term in a different context as a software for "recording" actions (mouse, keyboard actions in OS, for instance). Is there any connection between the different uses of the term?

3 Answers

In Ruby a macro is like a method, just some code, that instead of returning a Ruby datatype returns more Ruby code! This code will get executed along with all the other code you have written when you run your program.

I agreed with @Sergio as he explained 'A macro is a piece of code that generates some other code.' In example he explained:

attr_accessor :foo

Here attr_accessor is a macro that is generating some code automatically and we do not write this complete code.

I want to explain this with a simple example:

If you work in a large application with thousands of routes, a single config/routes.rb file can become cumbersome and hard to read because you will define all thousands of routes here.

So the solution is:

Step 1: We should define all routes in separate files inside the config directory.

Step 2: We will use draw macro to generate all file routes in routes.rb like mention below:

draw macro is using in routes file

Related