Class: RailsBootstrapTabs::Renderers::TabsRenderer

Inherits:
Object
  • Object
show all
Defined in:
lib/rails-bootstrap-tabs/renderers/tabs_renderer.rb

Defined Under Namespace

Classes: Context, Tab

Instance Method Summary collapse

Constructor Details

#initialize(template, *args, &block) ⇒ TabsRenderer

Returns a new instance of TabsRenderer.



3
4
5
6
7
8
9
# File 'lib/rails-bootstrap-tabs/renderers/tabs_renderer.rb', line 3

def initialize(template, *args, &block)
  @template = template
  @args = args || []
  @options = args[0] || {}
  @block = block
  @tabs = []
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(*args, &block) ⇒ Object



74
75
76
# File 'lib/rails-bootstrap-tabs/renderers/tabs_renderer.rb', line 74

def method_missing(*args, &block)
  @template.send(*args, &block)
end

Instance Method Details

#prepare_tabsObject



21
22
23
24
25
26
27
28
29
# File 'lib/rails-bootstrap-tabs/renderers/tabs_renderer.rb', line 21

def prepare_tabs
  @tabs.each.with_index do |tab, index|
    tab.options[:anchor] ||= "tab-#{index}-#{rstr}"
  end
  active_tab = @tabs.find { |t| t.options[:active] }
  active_tab ||= @tabs.first
  @tabs.each { |t| t.options.delete(:active) }
  active_tab.options[:active] = true if active_tab
end

#renderObject



15
16
17
18
19
# File 'lib/rails-bootstrap-tabs/renderers/tabs_renderer.rb', line 15

def render
  @block.call(Context.new(self))
  prepare_tabs
  render_tabs(@tabs) + render_panes(@tabs, @options)
end

#render_panes(tabs, options) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/rails-bootstrap-tabs/renderers/tabs_renderer.rb', line 42

def render_panes(tabs, options)
  content_class = 'tab-content'
  content_class << " #{options[:content_class]}" if options[:content_class]

   :div, class: content_class do
    tabs.map do |tab|
      options = tab.options
      pane_class = 'tab-pane'
      pane_class << ' active' if options[:active]
       :div, id: options[:anchor].to_s, class: pane_class do
        tab.block.call if tab.block
      end
    end.join("\n").html_safe
  end
end

#render_tabs(tabs) ⇒ Object



31
32
33
34
35
36
37
38
39
40
# File 'lib/rails-bootstrap-tabs/renderers/tabs_renderer.rb', line 31

def render_tabs(tabs)
   :ul, class: 'nav nav-tabs' do
    tabs.map do |tab|
      options = tab.options
       :li, class: ('active' if options[:active]) do
        link_to tab.name, "##{options[:anchor]}", data: { toggle: 'tab' }
      end
    end.join("\n").html_safe
  end
end

#rstrObject



11
12
13
# File 'lib/rails-bootstrap-tabs/renderers/tabs_renderer.rb', line 11

def rstr
  (0...8).map { ('a'.ord + rand(26)).chr }.join
end

#tab(name, options, &block) ⇒ Object



58
59
60
# File 'lib/rails-bootstrap-tabs/renderers/tabs_renderer.rb', line 58

def tab(name, options, &block)
  @tabs << Tab.new(name, options, block)
end