Pergunta

When I call a method foo() or refer to an attribute @bar in my view file, which object is going to respond?

For example if I have a partial _ebook.html.erb that looks like

<h2>Your eBook</h2>
<p>Title: <%= @title %></p>
<p>Due Date: <%= due_date(customer) %>
etc.

which object provides @title, due_date and customer? Do those bubble up to the BooksController and its modules/superclasses?

Also, if my render includes locals, for example

render partial: "ebooks", locals: {baz: @qux}

in which object is baz being stored?

Foi útil?

Solução 2

I've found most of the answer, at least for Rails 3.2.x. Here's my poorly written description:

As part of rendering, ActionView::Base#prepare creates an instance of an anonymous subclass of ActionView::Base and adds a couple of helper modules.

Then the view_assigns method stores the controller's instance variables in a hash in that instance.

The local variables are passed in as a hash and stored in an instance variable called locals in the same instance.

Outras dicas

It's not other objects provide your template with local variables, it's your template being read by the controller where the object exist in the context.

The erb template annotate variables such as @bar and taken by the controller to render accordingly. If controller actually has a @foo and you want to use it as the @bar in template you plugin locals: {bar: @foo}

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top