module RailsServersideDatatables::ViewHelpers

Public Instance Methods

serverside_datatable( serverside_path, id, config = {}, parameters = {} ) click to toggle source
# File lib/rails_serverside_datatables/views/view_helpers.rb, line 4
def serverside_datatable( serverside_path, id, config = {}, parameters = {} )
  # Our table requires an id
  config[ :id ] = id

  # Fetch the internal definition of the table
  raw_configuration = serverside_datatable_config_request( serverside_path, parameters )

  columns = []
  begin
    # Try to parse the (hopefully) JSON encoded response
    configuration = JSON.parse( raw_configuration )

    # Parse column information
    configuration[ 'columns' ].each do |column|
      columns.push( column.to_a.map { |f| [f.first.to_sym, f.last] }.to_h )
    end

  rescue Exception => e
    raise 'Auto config failed - invalid response. Could not parse response. Details: ' + e.message
  end

  # Required in erb file...
  filterable = columns.select { |c| c[:column_filtering] }


  # Render the actual content
  ERB.new(
      File.read( File.dirname( __FILE__ ) + '/datatable.html.erb' )
  ).result( binding ).html_safe
end

Private Instance Methods

serverside_datatable_config_request( url, parameters ) click to toggle source
# File lib/rails_serverside_datatables/views/view_helpers.rb, line 36
def serverside_datatable_config_request( url, parameters )
  parameters[ 'dt_config'  ]   = true

  # Route request internally
  request = Rack::MockRequest.env_for(
      url, params: parameters.to_query
  ).merge({ 'rack.session': session })
  
  # Fix for devise etc.
  request[ 'warden' ] = self.request.env[ 'warden' ] if self.request.key? 'warden'

  # Fetch configuration from the serverside definition
  response = Rails.application.routes.call( request )

  raise 'Auto config failed - invalid response. HTTP error code: ' + response.first unless response.first == 200

  # Return the acutal content
  response.last.body
end