Created
May 1, 2015 13:24
-
-
Save lukesmith/f8eba6172b69004c5fee to your computer and use it in GitHub Desktop.
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
class ActiveDataTables | |
def initialize(query, params) | |
@query = query | |
@params = params | |
end | |
def execute | |
total = @query.count | |
filtered = total # don't currently support filtering records so this will be the same as the total | |
apply_paging | |
apply_ordering | |
DataTablesResult.new(@params[:draw].to_i, @query, total, filtered) | |
end | |
def self.find(query, params) | |
new(query, params).execute | |
end | |
class DataTablesResult | |
attr_accessor :data, :draw, :records_total, :records_filtered | |
def initialize(draw, data, records_total, records_filtered) | |
@draw = draw | |
@data = data | |
@records_total = records_total | |
@records_filtered = records_filtered | |
end | |
def to_json | |
Jbuilder.encode do |json| | |
json.draw @draw | |
json.recordsTotal @records_total | |
json.recordsFiltered @records_filtered | |
json.data @data | |
end | |
end | |
end | |
private | |
def apply_paging | |
@query = @query.offset(@params[:start]).limit(@params[:length]) | |
end | |
def apply_ordering | |
order_instructions = @params[:order] || {} | |
columns = load_columns | |
order = {} | |
order_instructions.each_pair do |k, v| | |
column_index = v[:column] | |
column_name = columns[column_index.to_sym][:data] | |
order[column_name.to_sym] = v[:dir].to_sym | |
end | |
@query = @query.reorder(order) | |
end | |
def load_columns | |
@params[:columns] || {} | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment