○この記事の要点
「第4章 Rails風味のRuby」の途中まで実施内容メモ
思ったことなどのメモ
○第4章でやること
・3章で作成したプログラムを元に、Rils/Rubyの仕組みを学習
(ヘルパー、文字列とメソッド、オブジェクト、配列と範囲演算子、ハッシュ、クラス)
○内容
■ヘルパー
説明
・組み込みヘルパー:Railsの組み込み関数。自身で作成しなくても用意されている
例.app/views/layouts/application.html.erb で利用した
<%= stylesheet_link_tag …>
・カスタムヘルパー:自身で作成した関数
例.app/views/static_pages/home.html.erb で利用した
<% provide(:title, "Home") %>
作業
(1)カスタムヘルパーの作成
full_titleヘルパーは、ページごとのタイトルを返す。
タイトルが指定されなかった場合⇒Ruby on Rails Tutorial Sample Appとなるようにする
( | Ruby on Rails Tutorial Sample App とならないようにする)
module ApplicationHelper
# ページごとの完全なタイトルを返します。
def full_title(page_title = '')
base_title = "Ruby on Rails Tutorial Sample App"
if page_title.empty?
base_title
else
page_title + " | " + base_title
end
end
end
自動で実行するテストはこの時点では成功。
Homeのタイトルも「Home | Ruby on Rails Tutorial Sample App」になっている。
(2)app/views/static_pages/home.html.erb の先頭行<% provide(:title, "Home") %>を削除。文字列が与えられないようにしてみる。
<h1>Sample App</h1>
<p>
This is the home page for the
<a href="https://railstutorial.jp/">Ruby on Rails Tutorial</a>
sample application.
</p>
自動で実行するテストはこの時点でエラーになる。
Homeのタイトルが「Ruby on Rails Tutorial Sample App」になるが、テストは
「Home | Ruby on Rails Tutorial Sample App」が表示される想定になっている。
↓タイトルが想定している値と異なる。という内容。予想通り
11:46:12 - INFO - Running: test/controllers/static_pages_controller_test.rb
Running via Spring preloader in process 5247
/home/ubuntu/environment/sample_app/db/schema.rb doesn't exist yet. Run `rails db:migrate` to create it, then try again. If you do not intend to use a database, you should instead alter /home/ubuntu/environment/sample_app/config/application.rb to limit the frameworks that will be loaded.
Started with run options --seed 49053
FAIL["test_should_get_home", StaticPagesControllerTest, 0.27212137900005473]
test_should_get_home#StaticPagesControllerTest (0.27s)
<Home | Ruby on Rails Tutorial Sample App> expected but was
<Ruby on Rails Tutorial Sample App>..
Expected 0 to be >= 1.
test/controllers/static_pages_controller_test.rb:17:in `block in <class:StaticPagesControllerTest>'
5/5: [================================================================================================================] 100% Time: 00:00:00, Time: 00:00:00
Finished in 0.29195s
5 tests, 9 assertions, 1 failures, 0 errors, 0 skips
app/views/static_pages/home.html.erb を元に戻す。
<% provide(:title, "Home") %>
<h1>Sample App</h1>
<p>
This is the home page for the
<a href="https://railstutorial.jp/">Ruby on Rails Tutorial</a>
sample application.
</p>
テストのエラーがなくなる。
■感想
・ヘルパー⇒Viewで利用するメソッド的なもの。のはず。コントローラ、モデルではメソッドと言っているので。理解が違ったらご指摘ください。
・ゴールデンウィークが終わってしまったので、取り組む時間がなかったので少しだけしかできなかった。。。