Class: Breadcrumbs

Inherits:
Object
  • Object
show all
Defined in:
lib/breadcrumbs.rb,
lib/breadcrumbs/render.rb,
lib/breadcrumbs/version.rb,
lib/breadcrumbs/render/base.rb,
lib/breadcrumbs/render/list.rb,
lib/breadcrumbs/render/inline.rb,
lib/breadcrumbs/render/ordered_list.rb,
lib/breadcrumbs/action_controller_ext.rb

Defined Under Namespace

Modules: ActionController, Render, Version

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeBreadcrumbs

:nodoc:



9
10
11
# File 'lib/breadcrumbs.rb', line 9

def initialize # :nodoc:
  self.items = []
end

Instance Attribute Details

#itemsObject

Returns the value of attribute items.



7
8
9
# File 'lib/breadcrumbs.rb', line 7

def items
  @items
end

Instance Method Details

#add(text, url = nil, options = {}) ⇒ Object Also known as: <<

Add a new breadcrumbs.

breadcrumbs.add 'Home'
breadcrumbs.add 'Home', '/'
breadcrumbs.add 'Home', '/', class: 'home'

If you provide a symbol as text, it will try to find it as I18n scope.



22
23
24
25
26
# File 'lib/breadcrumbs.rb', line 22

def add(text, url = nil, options = {})
  options = {i18n: true}.merge(options)
  text = translate(text) if options.delete(:i18n)
  items << [text.to_s, url, options]
end

#render(options = {}) ⇒ Object

Render breadcrumbs using the specified format. Use HTML lists by default, but can be plain links.

breadcrumbs.render
breadcrumbs.render(format: 'inline')
breadcrumbs.render(format: 'inline', separator: '|')
breadcrumbs.render(format: 'list')
breadcrumbs.render(format: 'ordered_list')
breadcrumbs.render(id: 'breadcrumbs')
breadcrumbs.render(class: 'breadcrumbs')

You can also define your own formatter. Just create a class that implements a render instance method and you’re good to go.

class Breadcrumbs::Render::Dl
  def render
    # return breadcrumbs wrapped in a <DL> tag
  end
end

To use your new format, just provide the :format option.

breadcrumbs.render(format: 'dl')


54
55
56
57
58
59
60
61
62
# File 'lib/breadcrumbs.rb', line 54

def render(options = {})
  options[:format] ||= :list

  klass_name = options.delete(:format).to_s.classify
  klass = Breadcrumbs::Render.const_get(klass_name)
  html = klass.new(self, options).render

  html.respond_to?(:html_safe) ? html.html_safe : html
end

#translate(scope) ⇒ Object

:nodoc:



64
65
66
67
68
# File 'lib/breadcrumbs.rb', line 64

def translate(scope) # :nodoc:
  text = I18n.t(scope, scope: 'breadcrumbs', raise: true) rescue nil
  text ||= I18n.t(scope, default: scope.to_s) rescue scope
  text
end