Module: EffectiveBootstrapHelper

Defined in:
app/helpers/effective_bootstrap_helper.rb

Overview

Boostrap4 Helpers

Constant Summary collapse

COLLAPSE_SUBSTITUTIONS =

collapse(items.length, class: 'btn btn-primary', class: 'mt-2') do items.map { |item| content_tag(:div, item.to_s) }.join.html_safe end

{
  'Show ' => 'Hide ',
  'show ' => 'hide ',
  'Expand ' => 'Collapse ',
  'expand ' => 'collapse ',
  ' More' => ' Less',
  ' more' => ' less'
}
{class: "btn dropdown-toggle dropdown-toggle-split btn-sm btn-outline-primary", type: 'button', 'data-toggle': 'dropdown', 'aria-haspopup': true, 'aria-expanded': false}
{class: "btn dropdown-toggle btn-sm btn-outline-primary", type: 'button', 'data-toggle': 'dropdown', 'aria-haspopup': true, 'aria-expanded': false}
{class: 'btn-group'}
{class: 'btn-group dropleft', role: 'group'}
{class: 'dropdown-menu'}
{class: 'dropdown-menu dropdown-menu-right'}
'btn-sm btn-outline-primary'
"<span class='sr-only'>Toggle Dropdown</span>".html_safe
NUMBERS =
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']

Instance Method Summary collapse

Instance Method Details

#accordion(options = nil, &block) ⇒ Object

This is a special variant of collapse

accordion do

collapse('Add thing...') do

%p Something to add


10
11
12
13
14
15
16
17
18
19
# File 'app/helpers/effective_bootstrap_helper.rb', line 10

def accordion(options = nil, &block)
  (options ||= {})[:class] = "accordion #{options.delete(:class)}".strip

  id = "accordion-#{effective_bootstrap_unique_id}"

  @_accordion_active = id
  content = (:div, capture(&block), options.merge(id: id))
  @_accordion_active = nil
  content
end

#accordion_collapse(label, opts = {}, &block) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'app/helpers/effective_bootstrap_helper.rb', line 21

def accordion_collapse(label, opts = {}, &block)
  raise 'expected a block' unless block_given?

  id = "collapse-#{effective_bootstrap_unique_id}"
  show = (opts.delete(:show) == true)

  link_opts = { 'data-toggle': 'collapse', role: 'button', href: "##{id}", 'aria-controls': "##{id}", 'aria-expanded': show }

  link_opts[:class] = opts.delete(:link_class) || 'btn btn-link'
  div_class = opts.delete(:div_class)
  card_class = opts.delete(:card_class) || 'card card-body my-2'

  # Accordion collapse
  (:div, class: "card mb-0") do
    (:div, class: "card-header") do
      (:h2, class: "mb-0") do
        (:button, label, link_opts.merge(class: "btn btn-link"))
      end
    end +
    (:div, id: id, class: ['collapse', div_class, ('show' if show)].compact.join(' '), "data-parent": "##{@_accordion_active}") do
      (:div, capture(&block), class: "card-body")
    end
  end
end

#badge(value = nil, opts = {}) ⇒ Object Also known as: badges

https://getbootstrap.com/docs/4.0/components/badge/

badge('Warning', :secondary)

Can pass class or a context



49
50
51
52
53
54
55
56
57
58
59
60
# File 'app/helpers/effective_bootstrap_helper.rb', line 49

def badge(value = nil, opts = {})
  value = Array(value) - [nil, '']
  return if value.blank?

  badge_opts = opts
  badge_opts = {context: opts} unless badge_opts.kind_of?(Hash)

  context = badge_opts[:context].to_s.sub('badge-', '').presence || 'secondary'
  badge_opts[:class] ||= "badge badge-#{context}"

  value.map { |value| (:span, value, badge_opts) }.join(' ').html_safe
end

#bootstrap_breadcrumb(root_title: nil, root_path: nil, index_title: nil, index_path: nil, page_title: nil) ⇒ Object

Breadcrumb

https://getbootstrap.com/docs/4.0/components/breadcrumb/ Builds a breadcrumb based on the controller namespace, action and @page_title instance variable



450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
# File 'app/helpers/effective_bootstrap_helper.rb', line 450

def bootstrap_breadcrumb(root_title: nil, root_path: nil, index_title: nil, index_path: nil, page_title: nil)
  effective_resource = (@_effective_resource || Effective::Resource.new(controller_path))
  resource = instance_variable_get('@' + effective_resource.name) if effective_resource.name

  root_title ||= 'Home'
  root_path ||= '/'

  index_title ||= controller.class.name.split('::').last.sub('Controller', '').titleize
  index_path ||= effective_resource.action_path(:index) || request.path.split('/')[0...-1].join('/')

  page_title ||= (@page_title || resource&.to_s || controller.action_name.titleize)

  # Build items
  # An array of arrays [[title, url]]
  items = []

  # Namespaces
  Array(effective_resource.namespace).each do |namespace|
    items << [namespace.titleize, '/' + namespace]
  end

  # Home
  items << [root_title, '/'] unless items.present?

  # Controller index action
  items << [index_title, index_path] unless controller.action_name == 'index'

  # Always
  items << [page_title, nil]

  # Now take items and turn them into breadcrumbs
  (:ol, class: 'breadcrumb') do
    (items[0...-1].map do |title, path|
      (:li, link_to(title, path, title: title), class: 'breadcrumb-item')
    end + items[-1..-1].map do |title, path|
      (:li, title, class: 'breadcrumb-item active', 'aria-current': 'page')
    end).join.html_safe
  end
end

#bootstrap_paginate(collection, per_page:, url: nil, window: 2, collection_count: nil, render_single_page: false) ⇒ Object Also known as: paginate

limit(per_page).offset(offset) }

Add this to your controller: Add this to your view %nav= paginate(@posts, per_page: 10)



513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
# File 'app/helpers/effective_bootstrap_helper.rb', line 513

def bootstrap_paginate(collection, per_page:, url: nil, window: 2, collection_count: nil, render_single_page: false)
  raise 'expected an ActiveRecord::Relation' unless collection.respond_to?(:limit) && collection.respond_to?(:offset)

  collection_count ||= collection.limit(nil).offset(nil).count # You can pass the total count, or not.

  page = EffectiveResources.validate_page!(
    params[:page],
    collection_count: collection_count,
    per_page: per_page
  )
  last = (collection_count.to_f / per_page).ceil

  return unless (last > 1 || render_single_page) # If there's only 1 page, don't render a pagination at all.

  # Build URL
  uri = URI(url || request.fullpath)
  params = Rack::Utils.parse_nested_query(uri.query)
  url = uri.path + '?'

  # Pagination Tags
  prev_tag = (:li, class: ['page-item', ('disabled' if page <= 1)].compact.join(' ')) do
    link_to((:span, 'Previous'.html_safe), (page <= 1 ? '#' : url + params.merge('page' => page - 1).to_query),
      class: 'page-link', 'aria-label': 'Previous', title: 'Previous', 'aria-disabled': ('true' if page <= 1), 'tabindex': ('-1' if page <= 1), 'rel': ('prev' unless page <= 1)
    )
  end

  next_tag = (:li, class: ['page-item', ('disabled' if page >= last)].compact.join(' ')) do
    link_to((:span, 'Next'.html_safe), (page >= last ? '#' : url + params.merge('page' => page + 1).to_query),
      class: 'page-link', 'aria-label': 'Next', title: 'Next', 'aria-disabled': ('true' if page >= last), 'tabindex': ('-1' if page >= last), 'rel': ('next' unless page >= last)
    )
  end

  dots_tag = (:li, class: 'page-item disabled') do
    link_to('...', '#', class: 'page-link', 'aria-label': '...', 'aria-disabled': true, tabindex: '-1')
  end

  # Calculate Windows
  length = 1 + (window * 2)
  left = 1.upto(last).to_a.first(length)
  right = 1.upto(last).to_a.last(length)
  center = []
  max = length + 2

  if last <= max
    left = left - right
    right = right - left
  elsif left.include?(page + 1)
    right = [last]
    left = left - right
  elsif right.include?(page - 1)
    left = [1]
    right = right - left
  else
    left = [1]
    right = [last]
    center = (page - window + 1).upto(page + window - 1).to_a
  end

  # Render the pagination
  (:ul, class: 'pagination') do
    [
      prev_tag,
      left.map { |index| bootstrap_paginate_tag(index, page, url, params) },
      (dots_tag if last > max && left == [1]),
      center.map { |index| bootstrap_paginate_tag(index, page, url, params) },
      (dots_tag if last > max && right == [last]),
      right.map { |index| bootstrap_paginate_tag(index, page, url, params) },
      next_tag
    ].flatten.join.html_safe
  end
end

#bootstrap_paginate_tag(index, page, url, params) ⇒ Object



585
586
587
588
589
# File 'app/helpers/effective_bootstrap_helper.rb', line 585

def bootstrap_paginate_tag(index, page, url, params)
  (:li, class: ['page-item', ('active' if index == page)].compact.join(' '), title: "Page #{index}") do
    link_to(index, (url + params.merge('page' => index).to_query), class: 'page-link')
  end
end

#card(resource = nil, opts = {}, &block) ⇒ Object

https://getbootstrap.com/docs/4.0/components/card/

card('title do')

%p Stuff

card('Stuff', header: 'header title')

card(partial: 'lares/dashboard')



68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
# File 'app/helpers/effective_bootstrap_helper.rb', line 68

def card(resource = nil, opts = {}, &block)
  if resource.kind_of?(Hash)
    opts = resource; resource = nil
  end

  partial = opts.delete(:partial)
  locals = opts.delete(:locals) || {}

  raise('expected a block or a partial') unless block_given? || partial.present?

  return if resource.kind_of?(Class) && !EffectiveResources.authorized?(self, :index, resource)

  header = opts.delete(:header)
  title = opts.delete(:title) || opts.delete(:label) || effective_bootstrap_human_name(resource, plural: (opts.key?(:plural) ? opts.delete(:plural) : true))

  (:div, merge_class_key(opts, 'card mb-4')) do
    header = (:div, header, class: 'card-header') if header.present?

    body = (:div, class: 'card-body') do
      content = (partial.present? ? render(partial, locals) : capture(&block))

      if title.present?
        (:h5, title, class: 'card-title') + content
      else
        content
      end
    end

    header ? (header + body) : body
  end
end

#clipboard_copy(text, opts = {}) ⇒ Object



106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
# File 'app/helpers/effective_bootstrap_helper.rb', line 106

def clipboard_copy(text, opts = {})
  opts[:label] ||= 'Copy to Clipboard'
  opts[:class] ||= 'btn btn-secondary'

  label = (icon('clipboard', class: 'small-1') + ' ' + opts[:label]).html_safe

  (
    :button, 
    label, 
    class: ['btn-clipboard-copy', opts[:class]].compact.join(' '), 
    type: 'button', 
    'data-clipboard': text, 
    'data-clipboard-label': label
  )
end

#collapse(label, opts = {}, &block) ⇒ Object



151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
# File 'app/helpers/effective_bootstrap_helper.rb', line 151

def collapse(label, opts = {}, &block)
  raise 'expected a block' unless block_given?

  return accordion_collapse(label, opts, &block) if @_accordion_active

  id = "collapse-#{effective_bootstrap_unique_id}"
  show = (opts.delete(:show) == true)

  # The div and the card now
  div_class = opts.delete(:div_class)
  card_class = opts.delete(:card_class) || 'card card-body my-2'

  # Two link labels
  label_expand = opts.delete(:expand) || label.to_s.dup.tap do |label|
    COLLAPSE_SUBSTITUTIONS.each { |show, hide| label.sub!(hide, show) }
  end + icon('chevron-down')

  label_collapse = opts.delete(:collapse) || label.to_s.dup.tap do |label|
    COLLAPSE_SUBSTITUTIONS.each { |show, hide| label.sub!(show, hide) }
  end + icon('chevron-up')

  # The link html classes
  link_class = opts.delete(:link_class) || 'btn btn-link'
  link_class += ' effective-collapse-actions hidden-print'
  link_class += ' collapsed' unless show

  # Figure out all the button / link options
  link_opts = { 
    'data-toggle': 'collapse', 
    role: 'button', 
    href: "##{id}", 
    'aria-controls': "##{id}", 
    'aria-expanded': show, 
    class: link_class 
  }.merge(opts)

  # Normal collapse
  link_tag = (:a, link_opts) do
    (:div, label_expand.html_safe, class: 'collapse-label-expand') +
    (:div, label_collapse.html_safe, class: 'collapse-label-collapse')
  end

  div_tag = (:div, id: id, class: ['effective-collapse collapse', div_class, ('show' if show)].compact.join(' ')) do
    (:div, capture(&block), class: card_class)
  end

  link_tag + div_tag
end

#dashboard_card(partial, opts = {}) ⇒ Object

A card_dashboard card that renders one dashboard partial

dashboard_card('effective/polls/dashboard')



102
103
104
# File 'app/helpers/effective_bootstrap_helper.rb', line 102

def dashboard_card(partial, opts = {})
  card(merge_class_key(opts, 'card-dashboard').merge(partial: partial))
end

#dots(options = nil, &block) ⇒ Object

This is a special variant of dropdown dots do

dropdown_link_to 'Edit', edit_path(thing)



276
277
278
279
280
281
282
283
# File 'app/helpers/effective_bootstrap_helper.rb', line 276

def dots(options = nil, &block)
  (options ||= {})[:class] = "dropdown dropdown-dots #{options.delete(:class)}".strip

  (:div, options) do
    (:button, class: "btn btn-dots dropdown-toggle #{options.delete(:button_class)}", 'aria-expanded': true, 'aria-haspopup': true, 'data-toggle': 'dropdown', type: 'button') do
    end + (:div, capture(&block), class: 'dropdown-menu')
  end
end


285
286
287
288
289
# File 'app/helpers/effective_bootstrap_helper.rb', line 285

def dots_link_to(label, path, options = {})
  options[:class] = [options[:class], 'dropdown-item'].compact.join(' ')

  concat link_to(label, path, options)
end


224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
# File 'app/helpers/effective_bootstrap_helper.rb', line 224

def dropdown(variation: nil, split: true, btn_class: nil, btn_content: nil, right: false, &block)
  raise 'expected a block' unless block_given?

  btn_class ||= DROPDOWN_BTN_CLASS

  # Process all dropdown_link_tos
  @_dropdown_link_tos = []
  @_dropdown_split = split
  @_dropdown_button_class = btn_class
  yield

  return @_dropdown_link_tos.first if @_dropdown_link_tos.length <= 1

  # Build tags
  first = @_dropdown_link_tos.first

  button_opts = (split ? DROPDOWN_SPLIT_OPTS : DROPDOWN_UNSPLIT_OPTS)

  if btn_class != DROPDOWN_BTN_CLASS
    button_opts[:class] = button_opts[:class].sub(DROPDOWN_BTN_CLASS, btn_class)
  end

  button = (:button, button_opts) do
    btn_content || DROPDOWN_TOGGLE_DROPDOWN
  end

  menu_opts = (right ? DROPDOWN_MENU_RIGHT_OPTS : DROPDOWN_MENU_OPTS)

  menu = if split
    (:div, @_dropdown_link_tos[1..-1].join.html_safe, menu_opts)
  else
    (:div, @_dropdown_link_tos.join.html_safe, menu_opts)
  end

  @_dropdown_link_tos = nil

  if split && variation == :dropleft
    (:div, DROPDOWN_DROPLEFT_GROUP_OPTS) do
      (:div, (button + menu), DROPDOWN_DROPLEFT_OPTS) + first.html_safe
    end
  elsif split
    (:div, class: 'btn-group') do
      (:div, (first + button + menu), class: "btn-group #{variation}", role: 'group')
    end
  else
    (:div, (button + menu), class: 'dropdown')
  end
end


311
312
313
314
315
316
# File 'app/helpers/effective_bootstrap_helper.rb', line 311

def dropdown_clipboard_copy(text, opts = {})
  opts[:label] ||= 'Copy to Clipboard'

  options = { 'data-clipboard': text, 'data-clipboard-label': opts[:label], class: 'btn-clipboard-copy' }
  dropdown_link_to(opts[:label], '#', options.merge(opts))
end

Works with dots ao and dropdown do



319
320
321
322
323
324
325
326
327
328
# File 'app/helpers/effective_bootstrap_helper.rb', line 319

def dropdown_divider(options = {})
  options[:class] = [options[:class], 'dropdown-divider'].compact.join(' ')

  unless @_dropdown_link_tos
    (:div, '', options)
  else
    @_dropdown_link_tos << (:div, '', options)
    nil
  end
end

Works with dots do and dropdown do



292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
# File 'app/helpers/effective_bootstrap_helper.rb', line 292

def dropdown_link_to(label, path, options = {})
  btn_class = options.delete(:btn_class).presence || @_dropdown_button_class || 'btn-outline-primary'

  unless @_dropdown_link_tos
    options[:class] = (options[:class] ? "dropdown-item #{options[:class]}" : 'dropdown-item')
    return link_to(label, path, options)
  end

  if @_dropdown_link_tos.length == 0 && @_dropdown_split
    options[:class] = (options[:class] ? "btn #{btn_class} #{options[:class]}" : "btn #{btn_class}")
  else
    options[:class] = (options[:class] ? "dropdown-item #{options[:class]}" : 'dropdown-item')
  end

  @_dropdown_link_tos << link_to(label, path, options)

  nil
end

#effective_bootstrap_human_name(resource, plural: false, prefer_model_name: false) ⇒ Object



740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
# File 'app/helpers/effective_bootstrap_helper.rb', line 740

def effective_bootstrap_human_name(resource, plural: false, prefer_model_name: false)
  if resource.kind_of?(String)
    resource
  elsif resource.respond_to?(:datatable_name)
    et(resource)
  elsif resource.respond_to?(:model_name) == false
    resource.to_s
  elsif resource.kind_of?(ActiveRecord::Relation) || plural
    ets(resource)
  elsif resource.kind_of?(Class) || prefer_model_name
    et(resource)
  else
    resource.to_s
  end
end

#effective_bootstrap_sort_dropdown_content(content) ⇒ Object

Sorts the dropdown items of a nav_dropdown(sort: true) alphabetically by their label Each nav_divider starts a new section, and every section is sorted on its own, so the dividers keep grouping the menu just as they were written Any section with more than dropdown items in it is left exactly as-is



760
761
762
763
764
765
766
767
768
769
770
771
772
# File 'app/helpers/effective_bootstrap_helper.rb', line 760

def effective_bootstrap_sort_dropdown_content(content)
  divider = nav_divider

  sections = content.split(divider).map do |section|
    links = section.scan(/<a\b[^>]*>.*?<\/a>/m)
    remaining = links.inject(section) { |result, link| result.sub(link, '') }

    next section if remaining.present?
    links.sort_by { |link| link.gsub(/<[^>]*>/, '').strip.downcase }.join("\n")
  end

  sections.join("\n#{divider}\n").html_safe
end

#effective_bootstrap_unique_idObject



774
775
776
777
778
779
780
781
782
783
# File 'app/helpers/effective_bootstrap_helper.rb', line 774

def effective_bootstrap_unique_id
  # Set the first unique value
  @_effective_bootstrap_unique_id ||= Time.zone.now.to_i

  # Everytime we access this function make a new one
  @_effective_bootstrap_unique_id = @_effective_bootstrap_unique_id + 1

  # Return the updated value
  @_effective_bootstrap_unique_id
end

#list_group(&block) ⇒ Object



330
331
332
# File 'app/helpers/effective_bootstrap_helper.rb', line 330

def list_group(&block)
  (:div, yield, class: 'list-group')
end

List group

list_group_link_to

Automatically puts in the 'active' class based on request path



337
338
339
340
341
342
343
344
345
346
# File 'app/helpers/effective_bootstrap_helper.rb', line 337

def list_group_link_to(label, path, opts = {})
  # Regular link item
  opts[:class] = if request.fullpath.include?(path)
    [opts[:class], 'list-group-item list-group-item-action active'].compact.join(' ')
  else
    [opts[:class], 'list-group-item list-group-item-action'].compact.join(' ')
  end

  link_to(label.to_s, path, opts)
end

#merge_class_key(hash, value) ⇒ Object



730
731
732
733
734
735
736
737
738
# File 'app/helpers/effective_bootstrap_helper.rb', line 730

def merge_class_key(hash, value)
  return { :class => value } unless hash.kind_of?(Hash)

  if hash[:class].present?
    hash.merge!(:class => "#{hash[:class]} #{value}")
  else
    hash.merge!(:class => value)
  end
end

These two are used for advanced menus. When using content_for to capture inside nav dropdowns



427
428
429
430
# File 'app/helpers/effective_bootstrap_helper.rb', line 427

def nav_content_for(name, &block)
  raise('expected a block') unless block_given?
  content_for(name) { yield }
end


422
423
424
# File 'app/helpers/effective_bootstrap_helper.rb', line 422

def nav_divider
  (:div, '', class: 'dropdown-divider')
end


377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
# File 'app/helpers/effective_bootstrap_helper.rb', line 377

def nav_dropdown(label, right: false, groups: false, sort: false, link_class: [], list_class: [], &block)
  raise 'expected a block' unless block_given?

  id = "dropdown-#{effective_bootstrap_unique_id}"
  div_class = ['dropdown-menu', *('dropdown-menu-right' if right), *('dropdown-groups' if groups)].join(' ')

  # Render content
  @_nav_mode = :dropdown
  content = capture(&block)
  @_nav_mode = nil

  return ''.html_safe if content.blank?

  content = effective_bootstrap_sort_dropdown_content(content) if sort

  (:li, class: 'nav-item dropdown') do
    (:a, class: 'nav-link dropdown-toggle', href: '#', id: id, role: 'button', 'data-toggle': 'dropdown', 'aria-haspopup': true, 'aria-expanded': false) do
      label.html_safe
    end + (:div, class: div_class, 'aria-labelledby': id) do
      content.html_safe
    end
  end
end


432
433
434
435
436
437
438
439
440
441
442
443
# File 'app/helpers/effective_bootstrap_helper.rb', line 432

def nav_dropdown_content_for(name, &block)
  raise('expected a block') unless block_given?

  original = @_nav_mode

  begin
    @_nav_mode = :dropdown
    content_for(name) { yield }
  ensure
    @_nav_mode = original
  end
end


401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
# File 'app/helpers/effective_bootstrap_helper.rb', line 401

def nav_dropdown_group(label, unique: false, header: true, header_class: nil, &block)
  raise 'expected a block' unless block_given?

  div_class = [
    'dropdown-group',
    ("dropdown-group-#{effective_bootstrap_unique_id}" if unique),
    ("dropdown-group-first" if label.blank?),
    ("dropdown-group-#{label.to_s.parameterize}" if label.present?)
  ].compact.join(' ')

  header_class ||= 'dropdown-header'

  (:div, class: div_class) do
    if label.present? && header
      (:h6, label, class: header_class) + capture(&block)
    else
      capture(&block)
    end
  end
end

%ul.navbar-nav

nav_link_to 'Sign In', new_user_session_path

nav_dropdown 'Settings' do

= nav_link_to 'Account Settings', user_settings_path
= nav_divider
= nav_link_to 'Sign In', new_user_session_path, method: :delete

If you pass a class, it will authorize and display that class if you have :index access



359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
# File 'app/helpers/effective_bootstrap_helper.rb', line 359

def nav_link_to(resource, path, opts = {})
  return if resource.kind_of?(Class) && !EffectiveResources.authorized?(self, :index, resource)

  label = opts.delete(:label) || effective_bootstrap_human_name(resource, plural: (opts.key?(:plural) ? opts.delete(:plural) : true), prefer_model_name: true)

  if @_nav_mode == :dropdown  # We insert dropdown-items
    return link_to(label, path, merge_class_key(opts, 'dropdown-item'))
  end

  strict = opts.delete(:strict)
  active = (strict ? (request.fullpath == path) : request.fullpath.include?(path))

  # Regular nav link item
  (:li, class: (active ? 'nav-item active' : 'nav-item')) do
    link_to(label, path, merge_class_key(opts, 'nav-link'))
  end
end

#reveal_mail_to(email) ⇒ Object



594
595
596
597
# File 'app/helpers/effective_bootstrap_helper.rb', line 594

def reveal_mail_to(email)
  raise('expected an email') unless email.kind_of?(String) && email.include?('@')
  link_to 'Click to reveal email', '#', 'data-mailto-rot13' => email.tr('A-Za-z', 'N-ZA-Mn-za-m')
end

#tab(resource, opts = {}, &block) ⇒ Object



673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
# File 'app/helpers/effective_bootstrap_helper.rb', line 673

def tab(resource, opts = {}, &block)
  return if resource.kind_of?(Class) && !EffectiveResources.authorized?(self, :index, resource)
  plural = resource.kind_of?(ActiveRecord::Base) == false
  label = opts[:label] || effective_bootstrap_human_name(resource, plural: opts.fetch(:plural, plural), prefer_model_name: true)

  (@_tab_labels.push(label) and return) if @_tab_mode == :validate

  controls = opts[:controls] || label.to_s.parameterize.gsub('_', '-')
  controls = "item-#{controls}" if NUMBERS.include?(controls[0]) # Can't start with a number
  controls = controls[1..-1] if controls[0] == '#'
  controls = "#{controls}-#{@_tab_unique}" if @_tab_unique

  active = (@_tab_active == :first || @_tab_active == label)

  @_tab_active = nil if @_tab_active == :first

  if @_tab_mode == :tablist_vertical
    (:a, label, id: ('tab-' + controls), class: ['nav-link', ('active' if active)].compact.join(' '), href: '#' + controls, 'aria-controls': controls, 'aria-selected': active.to_s, 'data-toggle': 'tab', role: 'tab')
  elsif @_tab_mode == :tablist # Inserting the label into the tablist top
    (:li, class: 'nav-item') do
      (:a, label, id: ('tab-' + controls), class: ['nav-link', ('active' if active)].compact.join(' '), href: '#' + controls, 'aria-controls': controls, 'aria-selected': active.to_s, 'data-toggle': 'tab', role: 'tab')
    end
  else # Inserting the content into the tab itself
    classes = ['tab-pane', 'fade', ('show active' if active), opts[:class].presence].compact.join(' ')
    (:div, id: controls, class: classes, role: 'tabpanel', 'aria-labelledby': ('tab-' + controls), 'data-tab-label': label) do
      if @_tab_benchmarks.kind_of?(Hash)
        @_tab_benchmarks[label] = Benchmark.measure { yield }
      else
        yield
      end
    end
  end
end

#tabs(active: nil, unique: false, ignore_save_tab: false, benchmarks: EffectiveBootstrap.benchmarks, list: {}, content: {}, &block) ⇒ Object

If you pass active 'label' it will make that tab active. Otherwise first. Unique will make sure the tab html IDs are unique $('#tab-demographics').tab('show')



612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
# File 'app/helpers/effective_bootstrap_helper.rb', line 612

def tabs(active: nil, unique: false, ignore_save_tab: false, benchmarks: EffectiveBootstrap.benchmarks, list: {}, content: {}, &block)
  raise 'expected a block' unless block_given?

  # The Active Tab might be set from a previous form submission, or passed into helper
  tab_active = session[:_tabs].try(:pop) unless ignore_save_tab
  tab_active ||= active

  # If an active tab is passed, we validate we have a tab with that label, or fallback to first
  if tab_active.present?
    @_tab_mode = :validate
    @_tab_labels = []
    yield

    tab_active = nil unless @_tab_labels.include?(tab_active)
  end

  tab_active ||= :first if tab_active.nil?
  @_tab_unique = effective_bootstrap_unique_id if unique
  @_tab_benchmarks = {} if benchmarks # Enables benchmarks

  # Generate the html in two passes
  tabs_list = (:ul, {class: 'nav nav-tabs', role: 'tablist'}.merge(list)) do
    @_tab_mode = :tablist
    @_tab_active = tab_active

    yield # Yield to tab the first time
  end

  tabs_divs = (:div, {class: 'tab-content'}.merge(content)) do
    @_tab_mode = :content
    @_tab_active = tab_active

    yield # Yield to tab the second time
  end

  if benchmarks
    total = @_tab_benchmarks.values.sum(&:real)

    @_tab_benchmarks.each do |label, benchmark|
      percent = (benchmark.real / total * 100).round(0)
      amount = (benchmark.real * 1000).round(0)

      badge_class = case amount
      when (0.0..150.0) then ''
      when (150.0..500.0) then 'badge-warning'
      else 'badge-danger'
      end

      badge = (:span, "#{percent}% | #{amount}ms", class: "badge #{badge_class}")

      tabs_list.sub!(label, label + '<br>' + badge)
    end

    tabs_list = tabs_list.html_safe
  end

  (tabs_list + tabs_divs)
end

#vertical_tabs(active: nil, unique: false, list: {}, content: {}, &block) ⇒ Object



707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
# File 'app/helpers/effective_bootstrap_helper.rb', line 707

def vertical_tabs(active: nil, unique: false, list: {}, content: {}, &block)
  raise 'expected a block' unless block_given?

  @_tab_mode = :tablist_vertical
  @_tab_active = (active || :first)
  @_tab_unique = effective_bootstrap_unique_id if unique

  (:div, class: 'row border') do
    (:div, class: 'col-3 border-right') do
      (:div, {class: 'nav flex-column nav-pills my-2', role: 'tablist', 'aria-orientation': :vertical}.merge(list)) do
        yield # Yield to tab the first time
      end
    end +
    (:div, class: 'col-9') do
      (:div, {class: 'tab-content my-2'}.merge(content)) do
        @_tab_mode = :content
        @_tab_active = (active || :first)
        yield # Yield to tab the second time
      end
    end
  end
end