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:



13
14
15
# File 'lib/breadcrumbs.rb', line 13

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

Instance Attribute Details

#itemsObject

Returns the value of attribute items.



11
12
13
# File 'lib/breadcrumbs.rb', line 11

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.



26
27
28
29
30
# File 'lib/breadcrumbs.rb', line 26

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')


59
60
61
62
63
64
65
# File 'lib/breadcrumbs.rb', line 59

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

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

#translate(scope) ⇒ Object

:nodoc:



67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/breadcrumbs.rb', line 67

def translate(scope) # :nodoc:
  return scope if scope.match?(/\A[\s.]+\z/)

  text = begin
    I18n.t(scope, scope: "breadcrumbs", raise: true)
  rescue StandardError
    nil
  end

  text ||= begin
    I18n.t(scope, default: scope.to_s)
  rescue StandardError
    scope
  end

  text
end