Last active
April 18, 2020 06:57
-
-
Save amolpujari/ba1afda0a95399788147c06ac7590a99 to your computer and use it in GitHub Desktop.
rails 5 datatable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: true | |
class ApplicationDatatable | |
delegate :params, :link_to, :strip_tags, :local_time_ago, :local_date, :current_user, :avatar, | |
:avatar_link, :local_time, :admin?, to: :@view | |
def initialize view, options={} | |
@view = view | |
@options = options | |
@data_before_filter = total_collection | |
@data = @data_before_filter | |
apply_search | |
apply_status_filter | |
@data_after_filter = @data | |
prepare_data | |
end | |
def prepare_data | |
@prepared_data ||= collection. | |
order(sorting). | |
page(page).per(per_page). | |
includes([include_associations].flatten). | |
map{ |o| yield(o).map{ |o| o.to_s.gsub(/[\n ]+/," ").strip.html_safe } } | |
end | |
def as_json options={} | |
{ | |
sEcho: params[:sEcho].to_i, | |
iTotalRecords: @data_before_filter.count, | |
iTotalDisplayRecords: @data_after_filter.count, | |
aaData: @prepared_data, | |
} | |
end | |
def include_associations | |
[] | |
end | |
def collection | |
@data | |
end | |
def apply_search | |
if search.present? && @data.searchable? && !(::Rails.env.stage?) | |
@data = @data.where id: @data.search_ids(search) | |
end | |
end | |
def apply_status_filter | |
if status_filter.present? && status_filter[0] != "none" | |
@data = @data.where(status: status_filter) | |
end | |
end | |
def search | |
@search ||= params[:sSearch].to_s.gsub(/\s+/," ").strip[0..8] | |
end | |
def page | |
params[:iDisplayStart].to_i/per_page + 1 | |
end | |
def per_page | |
params[:iDisplayLength].to_i > 0 ? params[:iDisplayLength].to_i : 10 | |
end | |
def sorting | |
"#{sort_column} #{sort_direction}" | |
end | |
def sort_column | |
return @sort_column if defined? @sort_column | |
@sort_column = columns[params[:iSortCol_0].to_i] || columns[0] | |
@sort_column = :id if @sort_column == :uuid | |
@sort_column | |
end | |
def self.columns *args | |
@columns = args.to_a | |
end | |
def self._columns | |
@columns ||= [:id] | |
end | |
def columns | |
self.class._columns | |
end | |
def sort_direction | |
params[:sSortDir_0] == "asc" ? "ASC" : "DESC" | |
end | |
def status_filter | |
@status_filter ||= params[:sSearch_4].present? ? params[:sSearch_4].to_s.strip.split(",") : [] | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment