weppos / breadcrumbs_on_rails

A simple Ruby on Rails plugin for creating and managing a breadcrumb navigation.
https://simonecarletti.com/code/breadcrumbs-on-rails
MIT License
944 stars 188 forks source link

Unable to use CSS options for final elements in default builder #122

Closed dgarwood closed 4 years ago

dgarwood commented 6 years ago

I have a situation where the site CSS requires a specific CSS class added to the final element of the breadcrumb to result in a non-clickable link. Adding , option: {class: "class_name"} to the end of the add_breadcrumb call works fine for every element except the last one.

When adding breadcrumb elements like this:

class RoomsController < ApplicationController
  ...
  add_breadcrumb "Warehouses", :warehouses_path
  add_breadcrumb "Rooms", :warehouse_rooms_path, options: {class: "current"}
  ...

default builder output looks like:

<ul class="breadcrumbs">
    <li><a href="/warehouses">Warehouses</a></li>
    <li>Rooms</li>
</ul>

Due to CSS formatting on the site, I need output like:

<ul class="breadcrumbs">
    <li><a href="/warehouses">Warehouses</a></li>
    <li class="current">Rooms</li>
</ul>

Here's my new custom generator, the only difference is adding the element.options to the end of the @context.content_tag call:

# app/helpers/application_helper.rb
  ...
  class MyBuilder < BreadcrumbsOnRails::Breadcrumbs::SimpleBuilder
    def render
      @elements.collect do |element|
        render_element(element)
      end.join(@options[:separator] || " &raquo; ")
    end

    def render_element(element)
      if element.path == nil
        content = compute_name(element)
      else
        content = @context.link_to_unless_current(compute_name(element), compute_path(element), element.options)
      end
      if @options[:tag]
        @context.content_tag(@options[:tag], content, element.options) # <~~~ CHANGE HERE
      else
        ERB::Util.h(content)
      end
    end
  end
  ...

Haven't had a chance to write any tests on this, not sure if it would be helpful to everyone. Wanted to list this so that a) there's a clearer example of setting up a custom builder and b) reference this so myself or someone else can make a PR for this if desired.

dgarwood commented 6 years ago

for completeness, here's how i'm referencing the customer builder in layouts/application.rb

...
<div class="row">
  <ul class="breadcrumbs">
    <%= render_breadcrumbs builder: ApplicationHelper::MyBuilder, tag: :li, separator: ''%>
  </ul>
</div>
...
weppos commented 4 years ago

Closing as not actionable, keeping as example. Thanks for sharing it @dgarwood.