Tablets

Gem Version Code Climate Build Status

Installation

Add this line to your application's Gemfile:

gem 'tablets'

Include tablets and jquery datatables scripts in your app/assets/application.js:

//= require dataTables/jquery.dataTables
//= require tablets

Include jquery datatables styles in your app/assets/application.css:

 *= require dataTables/jquery.dataTables

Mount engine in config/routes.rb:

mount Tablets::Engine, at: '/tablets'

Examples

In app/tablets/posts.rb:

PostsTablet < Tablets::Base
  # Authorization logic.
  def authorize(controller)
    controller.current_user.id == params[:author_id]
  end

  # jQuery-datatables options overrides.
  def options
    { order: [0, 'asc'] }
  end

  # Columns definitions.
  def columns
    [{
      title: 'Title',
      data: :title,
      order: 'posts.title',
      search: 'posts.title',
      options: { className: 'post-title' }
    }, {
      title: 'User',
      data: proc do |post, controller|
        if post.user == controller.current_user
          'It is you'
        else
          [post.user.first_name, post.user.last_name].compact.join(' ')
        end
      end,
      order: ['users.first_name', 'users.last_name'],
      search: ['users.first_name', 'users.last_name']
    }]
  end

  # HTML for details area.
  def details(post)
    post.content.html_safe
  end

  # Process records before extracting data.
  def process(posts)
    posts.map { |post| post.use_wrapper }
  end

  # Data relation.
  def relation(params:, **)
    # Note: users joined to enable ordering.
    Post.joins(:users).where(user_id: params[:user_id])
  end

  # Additional data added to response.
  def payload
    { hash_with: 'data' }
  end
end

In app/views/posts/index.html.erb:

<%= render_tablet :posts, user_id: current_user.id %>

In app/assets/javascripts/posts.js:

$('.tablet[data-name="posts"]').on('click', 'tbody > tr[role=row]', function() {
  Tablets.toggleDetails($(this).closest('tr'));
});

Use '.tablet.has-details' for all tablets that has details.

JavaScript API

Fields:

tablet.element // root element
tablet.table   // jquery datatable object

Open details for row.

Tablets.toggleDetails($tr);

Returns nearest tablet:

Tablets.tabletForElement($element);

JavaScript callbacks

Callbacks called on tablet. You can use this to access tablet from callback.

Called just before datatable initialization.

Tablets.on('beforeInit', function(options) {});

Called after datatable initialization.

Tablets.on('afterInit', function() {});

Called before AJAX request is sent.

Tablets.on('beforeRequest', function(params) {});

Called after AJAX response is received.

Tablets.on('afterResponse', function(data) {});