How do templates get access to controller variables?


#1

This is probably more of a Ruby question than a Rails question. I’ve
always wondered exactly how controller instance variables are being made
accessible to the ERb code in the views.

In the Agile Rails book on pages 38, there’s a sidebar at the top that
hints at what’s going on:

“Rails does some Ruby magic so that the instance variables of the
controller object are injected into the tmeplate object”.

and then on the next page, this sentence appears as part of the “story
so far”:

  1. Rails processes this template through ERb… substituting in values
    set up by the controller.

I’m really interested in learning what Ruby language features made this
cool stuff possible. In general, how can I get one object to “know
about” or get references to private attributes of another object?

Thanks,
Jeff


#2

On Sat, Feb 25, 2006 at 05:06:09AM -0000, Jeff C. wrote:

This is probably more of a Ruby question than a Rails question. I’ve
always wondered exactly how controller instance variables are being made
accessible to the ERb code in the views.

Essentially a combination of Object#instance_variables and
Object#instance_variable_get, from one object (the controller instance)
to
another (the controller’s corresponding template object).

Check out add_instance_variables_to_assigns and its general area of
ActionController::Base.

actionpack/lib/action_controller/base.rb

They are basically just copied over one by one, save for a few which are
skipped for the sake of encapsulation.

marcel


#3

On Saturday, February 25, 2006, at 12:01 AM, Marcel Molina Jr. wrote:

Check out add_instance_variables_to_assigns and its general area of
ActionController::Base.

actionpack/lib/action_controller/base.rb

They are basically just copied over one by one, save for a few which are
skipped for the sake of encapsulation.

marcel

Thanks Marcel, that helps a lot.

By the way, thanks for the presentation on testing you did at the
Chicago ruby user’s group recently. I got a lot out of it.

Jeff
www.softiesonrails.com