Exposure of Variables

Learn and discuss the exposure of variables in Rails application.

Expose one instance variable per action

The way Rails makes data from controllers available to views is by copying the instance variables of the controller into the code for the view as instance variables with the same name. We highly suggest being ok with this design. We’ll talk about object orientation and controllers more in the chapter on controllers, but we don’t think there is high value in circumventing this mechanism with something that feels cleaner or more object-oriented.

That said, it’s possible to create quite a mess with instance variables, so that’s what we want to talk about here. The way to get the most of Rails’ design without creating a problem is to adopt two conventions:

  • Expose exactly one instance variable from any given action, ideally named for the resource or resources being manipulated by the route to that action. For example, the widget show page should only expose @widget.
  • There are exceptions: when a view requires access to reference data, like a list of country codes, when the view needs access to global context, like the currently logged-in user, or when there is UI state that is persisted across page refreshes, such as the currently selected tab in a tab navigation control.

These conventions are surprisingly easy to follow, but it does require doing a good job modelling your domain and resources. The key situation to avoid is exposing multiple instance variables that ...