Module: StimulusRailsDatatables::DatatableHelper

Defined in:
app/helpers/stimulus_rails_datatables/datatable_helper.rb

Defined Under Namespace

Classes: DatatableBuilder

Instance Method Summary collapse

Instance Method Details

#datatable_for(id, source:, order: [[2, 'desc']], **options, &block) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'app/helpers/stimulus_rails_datatables/datatable_helper.rb', line 5

def datatable_for(id, source:, order: [[2, 'desc']], **options, &block)
  classes = options.fetch(:classes, 'align-middle table w-100')
  searching = options.fetch(:searching, true)
  length_change = options.fetch(:length_change, true)
  state_save = options.fetch(:state_save, true)
  responsive = options.fetch(:responsive, true)
  columns = []

  capture(DatatableBuilder.new(self, columns), &block)
  datatable_columns = columns.map { |column| column.reject { |key, _| key == :header_content } }

  data = {
    controller: 'datatable',
    datatable_id_value: id,
    datatable_source_value: source,
    datatable_order_value: order.to_json,
    datatable_columns_value: datatable_columns.to_json,
    datatable_searching_value: searching,
    datatable_length_change_value: length_change,
    datatable_state_save_value: state_save,
    datatable_responsive_value: responsive
  }

  (:div, data: data) do
    (:table, class: classes, id: id) do
      (:thead, class: 'table-light align-middle') do
        (:tr) do
          safe_join(columns.map do |col|
            header = col[:header_content] || col[:title] || col[:data].to_s.titleize

            (:th, header, class: col[:class])
          end)
        end
      end
    end
  end
end