LoginSignup
0
2

More than 3 years have passed since last update.

railsでカスタムヘルパーの使い方

Last updated at Posted at 2021-01-20

引用先
Railsチュートリアル

カスタムヘルパーとは

Railsでは多くの組み込み関数が使えますが、使いたいメソッドがなかった時にオリジナルのメソッドを作成できます。
この新しく作ったメソッドのことをカスタムヘルパーといいます。

ファイルの場所

app/helpers/application_helper.rb
module ApplicationHelper

end

ファイルの位置は app/helpers/application_helper.rb
最初はこのようなファイル構造になっています。

使い方

例えばこのように記述する。

app/helpers/application_helper.rb
module ApplicationHelper

  def full_title(page_title = '')
    base_title = "Sample App"
    if page_title.empty?
      base_title
    else
      page_title + " | " + base_title
    end
  end
end

application.html.erbファイルの呼び出したい箇所へ記述。
今回はタイトルタグに記述します。

app/views/layouts/application.html.erb
<!DOCTYPE html>
<html>
  <head>
    <title><%= full_title(yield(:title)) %></title>
  </head>
  <body>
    <%= yield %>
  </body>
</html>

このように記述すれば、タイトルタグにヘルパーファイルに記述したこのコードが呼び出されます。

def full_title(page_title = '')
    base_title = "Sample App"
    if page_title.empty?
      base_title
    else
      page_title + " | " + base_title
    end
  end

# コード解説 
if文によって、page_titleが.empty?(入れ物が空→true,入れ物がある→false)

→true:base_title(Sample App)を表示
→false:page_title|base_title(Sample App)を表示

今回はコードの量が多くないため恩恵を感じにくいですが、コードを別ファイルに分けることでコードが見やすくなりますね。

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2