Let's separate the view from the application logic by moving the response HTML out of the app.rb
to a file named index.html
under a newly created views
directory.
<!-- views/index.html -->
<h1>All Articles</h1>
Now update the articles_controller.rb
to read the contents of this file to build the response. We will use the File#read
method to read the file.
require_relative 'application_controller'
class ArticlesController < ApplicationController
def index
index_file = File.join(Dir.pwd, "views", "index.html")
File.read(index_file)
end
end
A few things to note here:
- The
Dir.pwd
method returns the path to the current working directory of this process as a string. - The
File.join
method returns a new string formed by joining the strings using"/"
.
There are three benefits to separating the view from the application.
- The view gets its own
.html
orhtml.erb
file with the benefits that come with it, like IntelliSense and code organization. - Anytime you change the view, the application code picks it up automatically (even without the
Rack::Reloader
middleware), and they can vary on their own pace. - The biggest benefit is that the programmer and the designer can work on the Ruby and HTML code separately, without stepping over each others' toes. This was the major benefit Rails introduced in 2004, which was quite a big deal back then.
Refresh the browser to verify that everything is still working.