Skip to content

Instantly share code, notes, and snippets.

@AquisTech
Created March 21, 2016 05:26
Show Gist options
  • Save AquisTech/eaf735552ab936980005 to your computer and use it in GitHub Desktop.
Save AquisTech/eaf735552ab936980005 to your computer and use it in GitHub Desktop.
DRY AjaxDatatablesRails
class CoreAjaxDatatables < AjaxDatatablesRails::Base
def_delegators :@view, :link_to, :font_icon, :h
def sortable_columns
@sortable_columns ||= datatable_columns
end
def searchable_columns
@searchable_columns ||= datatable_columns
end
class << self
def model_name
name.gsub('Datatable', '')
end
def model
model_name.constantize
end
end
private
def data
records.map do |record|
attributes.map do |attr|
if attr.is_a?(Hash) && attr[:formatter]
value = record.send(attr[:name])
text = record.send(attr[:formatter])
h("<span data-search-value='#{value}'>#{text}</span>".html_safe)
else
h(record.send(attr))
end
end << *action_links(record)
end
end
def find_raw_records
self.class.model.all
end
alias get_raw_records find_raw_records
def datatable_columns
attributes.map do |attr|
"#{self.class.model_name}.#{attr.is_a?(Hash) && attr[:formatter] ? attr[:name] : attr}"
end
end
end
# TODOs
1. Support for associated models
2. Support for serielized models
3. Enable/disable search/sort for particular column
class User < ActiveRecord::Base
def formatted_country
# custom code to generate foramtted country. For example including flag and country name
end
end
class UserDatatable < CoreAjaxDatatables
def_delegators :@view, :user_path, :edit_user_path
private
def attributes
['first_name', 'last_name', { name: 'country_id', formatter: 'formatted_country' }]
end
def action_links(record)
[
link_to('Show', user_path(record)),
(record.archived? ? '' : link_to('Edit', edit_package_path(record))),
(record.archived? ? '' : link_to('Delete', user_path(record), method: :delete, data: { confirm: 'Are you sure?' }))
]
end
# can be overridden if needed
def find_raw_records
# custom query code
end
# can be overridden if needed
def datatable_columns
# different code than generated in CoreAjaxDatatables
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment