Exchanging data between the controller and the views is a common task in web application development. This task shows you how to set an instance variable in the controller and access its value from the view.
Open <JRUBY_HOME>/samples/hello/app/controllers/home_controller.rb in a text editor.
Add an instance variable called @hello_message to the action called index, so that the controller looks like this:
class HomeController < ApplicationController def index @hello_message = "Welcome to JRuby on Rails on the Sun GlassFish Enterprise Server" end end
In Rails, the actions are supposed to map to views. So, when you access the index.html.erb file, the index action executes. In this case, it makes the @hello_message variable available to index.html.erb.
Save the file.
Open <JRUBY_HOME>/samples/hello/app/views/home/index.html.erb file in a text editor.
At the end of the file, add the following output block:
<%= @hello_message %>
This JRuby code embedded into the view, inserts the value of @hello_message into the page. When you run the application, you can see “Welcome to JRuby on Rails on the GlassFish Enterprise Server” in your browser.
Save the file.