LoginSignup
1
0

More than 3 years have passed since last update.

breadcrumbs_on_railsを使ったパンくず実装 その② オリジナルviewを使おう

Last updated at Posted at 2020-03-20

パンくず実装の続きです。
といっても備忘録としての記事ですので、ほぼほぼサイトを参照してやったことを思い返すつもりで書いています。

ちなみに今回は、lib直下をいじりますので、少し習ったことがないことをしました。
ではでは、やっていきましょうか

まずは、custom builder を作りましょう。
といってもこの名称はなんでも良いです。
ただし、ほぼほぼコードの直打ちで作りますよ。

/lib/custom_breadcrumbs_builder.rb
class CustomBreadcrumbsBuilder < BreadcrumbsOnRails::Breadcrumbs::Builder
  def render
    @context.render '/shared/breadcrumbs', elements: @elements
  end
end

これは、views/sharedフォルダにオリジナルのviewを呼びにいっているという記述です。
render形式のため、elements:@elementsの要素をbreadcrumbs.html.hamlへ送っています。
shardフォルダにrenderさせるファイルを纏めているので、そこを呼んでいますが、別に場所はどこでも良いです。

/view/breadcrumbs.html.haml
- if elements.present?
  %ul.l-gretel-brock
    - elements.each do |element|
      %li.l-gretel-inline
        - if element.path.present?
          = link_to element.name ,element.path, class: 'l-gretel-link u-deco-none'
          = fa_icon 'chevron-right', class: 'l-gretel-icon'
        - else
          = element.name
    = elements.last.name

と書きますわね。CSSは適当煮付けてくださいな。
(gretelって名称使ってるけどむしろわかりづらいような・・・)

そして、使いたいところに、以下の一文を追加する。

test.html.haml
  = render_breadcrumbs builder: ::CustomBreadcrumbsBuilder

最後に、config/application.rbに以下の一文を追加しよう。

config/application.rb
module Test
  class Application < Rails::Application
    config.autoload_paths += %W(#{config.root}/lib) #ここの一文だけだよ!
end

これはローカル上で、lib直下にあるファイルを呼びに行きますよということです。

ここまでできれば一安心、早速みてみよう!
いかのように表示されました。
fa_iconが良い感じです。

Screenshot from Gyazo

ここまでやってみてダメだった人は、rails sして再起動、もしくはbandle installを試してみよう。
私は意外と忘れるアプリケーションサーバーの再起動は盲点でした。

あ、あと本番環境は、以下の一文追加必要ですので、ご注意ください。
いくつか文章探しましたが、これでやっと通った感じです。

config/environments/production.rb
Rails.application.configure do
###いっぱい文章ありましたが省略
  config.eager_load_paths += %W( #{config.root}/lib )
end

これで、デプロイしても問題ないはず!

試してみてください。
ちなみに参考した記事は以下の通り、私もtech:expert生です。
https://pg-happy.jp/rails-pankuzu-list.html

1
0
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
1
0