In chapter 9 of Agile Web development with Rails 4
You have a model cart.rb which has many line items
class Cart < ActiveRecord::Base
has_many :line_items, dependent: :destroy
end
You also have a line items model
class LineItem < ActiveRecord::Base
belongs_to :product
belongs_to :cart
end
in controllers/concerns you define a module current cart
module CurrentCart
extend ActiveSupport::Concern
private
def set_cart
@cart = Cart.find(session[:cart_id])
rescue ActiveRecord::RecordNotFound
@cart = Cart.create
session[:cart_id] = @cart.id
end
end
When you add a line item, you call the create method of line_items_controller. Before create method is called, it calls the set_cart method of the current cart module by such
before_action :set_cart, only: [:create]
After line item is posted, it redirects the page to the cart index page as such
format.html { redirect_to @line_item.cart, notice: 'Line item was successfully created.' }
When the view is displayed, it uses
<% @cart.line_items.each do |item| %>
<li><%= item.product.title %></li>
<% end %>
My question is how does this view have access to @cart instance variable which is defined in the current_cart module?