Skip to content

Instantly share code, notes, and snippets.

@dpaluy
Created March 18, 2021 21:43
Show Gist options
  • Select an option

  • Save dpaluy/014166aa521f78cde2c81b60d51e841c to your computer and use it in GitHub Desktop.

Select an option

Save dpaluy/014166aa521f78cde2c81b60d51e841c to your computer and use it in GitHub Desktop.
Breadcrumbs in Rails
<head>
<title>
<%= breadcrumbs.map(&:name).reverse.append("My App").join(" | ") %>
</title>
</head>
<nav>
<ol class="breadcrumbs">
<% breadcrumbs.each do |crumb| %>
<li>
<% if crumb.link? %>
<%= link_to crumb.name, crumb.path, class: "breadcrumb-link" %>
<% else %>
<span class="breadcrumb-page">
<%= crumb.name %>
</span>
<% end %>
<% unless crumb == breadcrumbs.last %>
<span class="breadcrumb-separator">/</span>
<% end %>
</li>
<% end %>
</ol>
</nav>
class ApplicationController < ActionController::Base
...
helper_method :breadcrumbs
def breadcrumbs
@breadcrumbs ||= []
end
def add_breadcrumb(name, path = nil)
breadcrumbs << Breadcrumb.new(name, path)
end
end
class Breadcrumb
attr_reader :name, :path
def initialize(name, path)
@name = name
@path = path
end
def link?
@path.present?
end
end
class PostsController < ApplicationController
before_action :set_breadcrumbs
def index
@posts = Post.all
end
def show
@post = Post.find(params[:id])
add_breadcrumb(@post.title, @post)
end
def new
@post = Post.new
add_breadcrumb("New Post")
end
private
def set_breadcrumbs
add_breadcrumb("Admin", admin_home_path) if Current.user.admin?
add_breadcrumb("Posts", posts_path)
end
end
@dpaluy
Copy link
Author

dpaluy commented Mar 18, 2021

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment