Frage

Look at this Devise migration template and you will see that it has erb syntax.

How does the Ruby interpreter interpret an rb file with erb content without throwing a SyntaxError?

# migration.rb inside active record generator templates.
class DeviseCreate<%= table_name.camelize %> < ActiveRecord::Migration
  # snip more erb
end
War es hilfreich?

Lösung

That template is processed by ERB at the time you run generator, and the result will be stored in your Rails project.

It means in your Rails project only the result file is stored and executed. In the Rails codebase templates for generator uses a .tt extension, that makes more explicit that the file is just a template and will not be stored verbatim in your project.

In other words, your project will not contain this template as it is, but the result applied to the context where you run the generator. For instance,

class DeviseCreate<%= table_name.camelize %> < ActiveRecord::Migration

will become

class DeviseCreateUsers < ActiveRecord::Migration

Andere Tipps

You are right, it will raise SyntaxError if interpreted directly by ruby, but that's not the case here and i guess you already figured that Rails took that file and treated it as an ERB template (read more about erb here)

Well, from the docs:

In Rails 3.0 and above, generators don't just look in the source root for templates, they also search for templates in other paths. And one of them is lib/templates.

Source: http://guides.rubyonrails.org/generators.html#customizing-your-workflow-by-changing-generators-templates

So your file is just like the helper.rb in the docs example and the erb snippets are evaluated by Rails when the generator is invoked.

You could ofcourse try to digg deeper and find where in rails source code this behavior (evaluating generators templates .rb as erb) is implemented but i am afraid i won't be much of a help in that not yet at least :)

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top