4

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 3

5

In this context, a macro is a piece of code that generates some other code. For example:

attr_accessor :foo

generates this:

def foo
  @foo
end

def foo=(val)
  @foo = val
end

Is there any connection between the different uses of the term?

Kind of. You could say that author of attr_accessor "recorded" what it should expand to.

2
  • There is no such thing as “ruby macros.” These hipsters from Rails world are just weak in naming :-P Jun 2, 2017 at 6:54
  • @mudasobwa: depends on your definition of "macro" :) Jun 2, 2017 at 7:11
2

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.

0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.