Module: AjaxDatatablesRails::AltApi::Datatable::ClassMethods

Defined in:
lib/ajax-datatables-rails/alt-api/datatable.rb

Overview

module class methods

Instance Method Summary collapse

Instance Method Details

#base_model(model_class) ⇒ Object

This is the primary ActiveRecord model the datatable represents. For example, if you have writing a UserDatatable, and that is a list of User records, ‘User’ would be the base model.



27
28
29
# File 'lib/ajax-datatables-rails/alt-api/datatable.rb', line 27

def base_model(model_class)
  @base_model = model_class
end

#column(*new_column_args, &block) ⇒ Object

This adds a ColumnDef to the columns. Order in which column is called is important. The column order is the same as they will be returned to the client. To see a full list of options, see the ColumnDef class.



34
35
36
# File 'lib/ajax-datatables-rails/alt-api/datatable.rb', line 34

def column(*new_column_args, &block)
  columns << ColumnDef.new(*new_column_args, &block)
end

#column_paramsObject

This is used for tests



70
71
72
73
74
75
# File 'lib/ajax-datatables-rails/alt-api/datatable.rb', line 70

def column_params
  new({}).columns.map(&:as_json).each_with_index.reduce({}) do |accum, (h, i)|
    accum[i] = { **h, search: { value: '', regex: 'false' } }
    accum
  end
end

#columnsObject



38
39
40
# File 'lib/ajax-datatables-rails/alt-api/datatable.rb', line 38

def columns
  @columns ||= []
end

#js_columns(only: [], exclude: []) ⇒ Object

Use this in the ‘columns` option in the JS initialization of Datatable. Call this method in the view. There are times that when conditionally showing columns, the column conditionals need access to the datatable instance. Example:

<table data-datatable-columns="<%= UsersDatatable.js_columns %>">
  <th>Name</th>
  <th>Email</th>
</table>
<script>
  var table = $('#my-datatable');
  table.DataTable({
    columns: JSON.parse(table.data('datatable-columns'))
  })
</script>


57
58
59
60
61
62
63
64
65
66
67
# File 'lib/ajax-datatables-rails/alt-api/datatable.rb', line 57

def js_columns(only: [], exclude: [])
  cols = if only.present?
           columns.select { |c| only.include?(c.attr_name) }
         elsif exclude.present?
           columns.reject { |c| exclude.include?(c.attr_name) }
         else
           columns
         end
  cols.reject! { |c| c.attr_name.to_s.starts_with?('search_only') }
  cols.map(&:as_json).compact.to_json
end

#search_only_attributes(attrs) ⇒ Object



77
78
79
80
81
82
# File 'lib/ajax-datatables-rails/alt-api/datatable.rb', line 77

def search_only_attributes(attrs)
  attrs.each do |attr|
    key_name = :"search_only__#{attr.downcase.tr('.', '_')}"
    columns << ColumnDef.new(key_name, source: attr, search_only: true)
  end
end