This article deepens my understanding by writing a Rails tutorial commentary article to further solidify my knowledge It is part of my study. In rare cases, ridiculous content or incorrect content may be written. Please note. I would appreciate it if you could tell me implicitly ...
Source Rails Tutorial
We will comprehensively learn how to create a Rails application by creating a Twitter-like sample application Sample_app. This chapter starts by creating a new project Sample_app.
I wrote articles in quite detail up to Chapter 2, but after Chapter 3 The amount of code will increase considerably, so what you can do by reading the Rails tutorial I'll abbreviate it ...
Create a new Sample_app Update the Gemfile. Don't forget --without production because you don't want to install the production pg gem again this time. Since it is a new application, initialize the Git repository. Rewrite the README here as well. After rewriting the README, commit it for the time being. Also create a remote repository for Sample_app on Github. After creating a remote repository, push it In case of Cloud9 environment, edit development.rb so that the application can be started locally. For the time being, just add the code for hello and world display as in Chapter 2 and push it to heroku.
`heroku domains`
.As a development habit, instead of always working on the master branch, create a topic branch each time you implement something It is said that it is a good habit to work. By doing so, it is easy to divide the work. Easy to see the work There are various advantages. From this time on, I will create a topic branch and work on it.
$ git checkout -b static-pages
I will create it from the controller for static pages at once
$ rails g controller StaticPages home help
generate may be the abbreviation g There are other abbreviations, and it's a good idea to remember them.
Complete command | Shortened form |
---|---|
$ rails server | $ rails s |
$ rails console | $ rails c |
$ rails generate | $ rails g |
$ rails test | $ rails t |
$ bundle install | $ bundle |
From Rails Tutorial 6th Edition https://railstutorial.jp/chapters/static_pages?version=6.0#table-shortcuts
For now, push the static-pages branch remotely
Setting origin to static-pages upstream with the -u option
After that, you can do the same push with just git push
.
When the controller is automatically generated by the generate command, the routes.rb file is also automatically updated. In this case, I created a home action and a help action with generate.
routes.rb
Rails.application.routes.draw do
get 'static_pages/home'
get 'static_pages/help'
# For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
root "application#hello"
end
The routing rules for the home and help actions are set automatically. Start up the local server and display the home page of static_pages.
Rails will refer to the router when you specify the URL (this time / static_pages / home) Perform the action of the corresponding controller. (Home action of StaticPages controller) After that, the view corresponding to the action is output. The static page controller doesn't change content each time, so the action is empty (same page content).
$ rails g controller Foo bar baz
$ rails d controller Foo
The home page and help page created in the current state are completed in HTML and are completely static pages. In other words, it is a page that can be edited without knowledge of Rails. Here, as in Chapter 2, you can get user data or post data according to the content. Rails knowledge (ERB) is required for actions that change the display content (dynamic).
Before adding the about page, write a test for the about page in advance. Since the generate command automatically generates tests for the home and help pages First of all, run a test to confirm that there is no problem at this time
$ rails t
...
Finished in 6.708000s, 0.2982 runs/s, 0.2982 assertions/s.
2 runs, 2 assertions, 0 failures, 0 errors, 0 skips
Red The Test Driven Development (TDD) cycle Write tests that fail (tests for unimplemented features, etc.) → Fail (RED) Write the actual application code and pass the test written earlier → Success (GREEN) 3 steps of refactoring (REFACTOR)
Based on this, I will write a test of the About page that I have not made yet
static_pages_controller_test.rb
require 'test_helper'
class StaticPagesControllerTest < ActionDispatch::IntegrationTest
...
test "should get about" do
get static_pages_about_url
assert_response :success
end
end
This code sends a GET request to the about page of static_pages I am testing the content that the response code is 200 OK (success).
Of course, I haven't implemented any About page yet, so I get the error as expected.
Green Take a look at the error message
Error:
StaticPagesControllerTest#test_should_get_about:
NameError: undefined local variable or method `static_pages_about_url' for #<StaticPagesControllerTest:0x000055b65cfc03b0>
test/controllers/static_pages_controller_test.rb:15:in `block in <class:StaticPagesControllerTest>'
If you read it in detail In StaticPagesControllerTest should_get_about No method is defined for static_pages_about_url (there is no URL for About) Is angry.
This is because I haven't set up routing
Let's add routing at once.
in routes.rb
get 'static_pages/about'
To add.
Adding a route enables a helper called static_pages_about_url.
If you run the test again, this time
Error:
StaticPagesControllerTest#test_should_get_about:
AbstractController::ActionNotFound: The action 'about' could not be found for StaticPagesController
test/controllers/static_pages_controller_test.rb:15:in `block in <class:StaticPagesControllerTest>'
This is also a simple error I'm angry that I can't find the about action. This is the result of adding routing to refer to the about action of the static_pages controller.
Let's add an About action right away
def about
end
Just write this inside the static_pages controller The content of the action is still a completely static page like home and help, so empty is OK
If you run the test with this, this time
Error:
StaticPagesControllerTest#test_should_get_about:
ActionController::MissingExactTemplate: StaticPagesController#about is missing a template for request formats: text/html
test/controllers/static_pages_controller_test.rb:15:in `block in <class:StaticPagesControllerTest>'
This is angry that the about template (view) cannot be found.
This is also supported by adding a view. Add about.html.erb in app / views / static_pages.
The test succeeds (GREEN) in this state
Finished in 0.976764s, 3.0714 runs/s, 3.0714 assertions/s.
3 runs, 3 assertions, 0 failures, 0 errors, 0 skips
Change the title dynamically. Disable layout for study
$ mv app/views/layouts/application.html.erb layout_file
This command temporarily renames and moves the layout file application.html.erb to disable it.
Write the title test first The title should change from page to page, so the code looks like this.
test "should get home" do
get static_pages_home_url
assert_response :success
assert_select "title", "Home | Ruby on Rails Tutorial Sample App"
end
test "should get help" do
get static_pages_help_url
assert_response :success
assert_select "title", "Help | Ruby on Rails Tutorial Sample App"
end
test "should get about" do
get static_pages_about_url
assert_response :success
assert_select "title", "About | Ruby on Rails Tutorial Sample App"
end
Select the title tag and make sure that its contents match. Of course, the test is RED because it is not implemented
First, rewrite the view of the home, help, about page.
Since I set a title for each page, the test will be GREEN.
Finished in 0.062407s, 48.0717 runs/s, 96.1433 assertions/s.
3 runs, 6 assertions, 0 failures, 0 errors, 0 skips
def setup
@base_title = "Ruby on Rails Tutorial Sample App"
end
test "should get home" do
get static_pages_home_url
assert_response :success
assert_select "title", "Home | #{@base_title}"
end
test "should get help" do
get static_pages_help_url
assert_response :success
assert_select "title", "Help | #{@base_title}"
end
test "should get about" do
get static_pages_about_url
assert_response :success
assert_select "title", "About | #{@base_title}"
end
At this stage, most of the HTML structure (basic tags such as head) is duplicated on all home, help, and about pages. The title is also the same for the Ruby on Rails Tutorial Sample App. It is important to remove such duplication and DRY.
provide method in view
symbol,"String")By specifying
You can call the string associated with the symbol with yield.
Ruby code can be used in views
The view is embedded Ruby [ERB (Embedded RuBy)] is a file in the format that allows you to embed Ruby in HTML.
Enclose it in <%%> and just execute the statement inside
The difference is that if you enclose it in <% =%>, the statement inside will be executed and the result will be inserted into the template.
Here is the result of rewriting the title part using this mechanism
```erb
<% provide(:title,"Help") %>
<!DOCTYPE html>
<html>
<head>
<title><%= yield(:title) %> | Ruby on Rails Tutorial Sample App</title>
</head>
Of course, the test also passes.
If this is left as it is, common parts will remain, so I will refactor it immediately. First, enable the layout file that you disabled earlier
mv layout_file app/views/layouts/application.html.erb
Then, replace the title tags individually placed in home, help, and about with the title tags of the layout file.
erb:application.html.erb
<!DOCTYPE html>
<html>
<head>
<title><%= yield(:title)%> | Ruby on Rails Tutorial Sample App</title>
<%= csrf_meta_tags %>
<%= csp_meta_tag %>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
<%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
</head>
<body>
<%= yield %>
</body>
</html>
The contents of the view of each page are substituted as they are in the yield part. In other words, what is displayed when trying to display each page It is application.html.erb that loaded the view of each page.
After that, extra things such as html tags are left in the view of each page, and as it is, application.html.erb Since it will be duplicated, delete unnecessary parts and make the view of each page only the content.
erb:help.html.erb
<% provide(:title,"Help") %>
<h1>Help</h1>
<p>
Get help on the Ruby on Rails Tutorial at the
<a href="https://railstutorial.jp/help">Rails Tutorial help page</a>.
To get help on this sample app, see the
<a href="https://railstutorial.jp/#ebook"><em>Ruby on Rails Tutorial</em>
book</a>.
</p>
static_pages_controller_test.rb
test "should get contact" do
get static_pages_contact_url
assert_response :success
assert_select "title", "Contact | #{@base_title}"
end
After that, add the contact routing to routes.rb and Add a contact action to static_pages_controller and Just create a contact view.
Finished in 1.044651s, 3.8290 runs/s, 7.6581 assertions/s.
4 runs, 8 assertions, 0 failures, 0 errors, 0 skips
The test also passes.
For the time being, I set the hello action to display hello, world in the root URL to deploy.
I made a home page this time, so I will move it there
root 'static_pages/home'
static_pages_controller_test.rb
test "should get root" do
get root_url
assert_response :success
end
Error:
StaticPagesControllerTest#test_should_get_root:
NameError: undefined local variable or method `root_url' for #<StaticPagesControllerTest:0x000055d85cb31200>
test/controllers/static_pages_controller_test.rb:10:in `block in <class:StaticPagesControllerTest>'
I got an error if the root_url method was not defined.
You can see that the root_url helper can be used by setting the rootURL.
Since the work of Chapter 3 has been completed Commit If you run the test when deploying, you won't have to worry about finding bugs after deploying.
Recommended Posts