Wednesday, September 3, 2014

DataTables.net + JRuby & Sinatra

I found the examples in DataTables.net jQuery table plugin worked well but I didn't know how easy it would be to use in an actual app. It took only a few minutes to get a Sinatra app in place which supplied JSON to the DataTables ajax example. Only one change had to be made to the Javascript and that is shown in the last code snippet, below.

I downloaded DataTables and in the DataTables folder I created a "public" folder and moved all the DataTables files and folders into the public folder. In the DataTables folder, I created datatables.rb and the logs folder and an empty logs/log.txt file. I added the jdbc jar file to the lib folder and the yml file to the config folder. In your db.yml file, you will need to replace SEWDEV with the name of the DB server you use and, of course, a username and password that are valid for your database.

I found that the data used in the "Ajax sourced data" example is in public/examples/ajax/data/arrays.txt so I took that data and changed it into the SQL insert statement you see in this gist. I created the table and ran the insert statement.

I then found that the reference to the arrays.txt file is in public/examples/data_sources/ajax.html so I modified the ajax function in that file to use data from the "/employees" link as shown below.

Run datatables.rb with the command "jruby datatables.rb". This starts the WEBrick server on port 4567.

Direct your browser to http://localhost:4567/ and the Sinatra app will redirect you to examples/index.html

Under the Resources topic, click on the "Ajax sourced data" link. That link takes the browser to the ajax.html file we changed. The data now comes from the "/employees" link which is handled by the JRuby program.