ajax_table_rails 0.0.1

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 135199e12d3994cb2cd2ca99096927029366910b
4
+ data.tar.gz: c73f7a30edcd5f8b9685577b7d048d91b3f1a180
5
+ SHA512:
6
+ metadata.gz: 9ca2d2d538d6a6e1ae355d68bbfb3502b4de9370905ca02603a2bc9fb1353b71ca57d92474b072d9f2649f20cd8fbe9dbef45e7e287cdabaa4c0983e1526dd5f
7
+ data.tar.gz: 536c0b373cc3959ed3c10ab27916079b824dce0f64aea7081ecbf1bd4e23adf1e8999f0ae3d4a576a3693282ec62330b00f27a3b329f898a0c93a2fcf97d64e1
data/.gitignore ADDED
@@ -0,0 +1,4 @@
1
+ *.gem
2
+ .bundle
3
+ Gemfile.lock
4
+ pkg/*
data/CHANGELOG.md ADDED
@@ -0,0 +1,3 @@
1
+ ## v0.0.1
2
+
3
+ * Initial release
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source "https://rubygems.org"
2
+
3
+ # Declare your gem's dependencies in ajax_table_rails.gemspec.
4
+ gemspec
data/MIT-LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ Copyright 2014 Yuval Kordov
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,150 @@
1
+ # AjaxTableRails
2
+
3
+ AjaxTableRails is a super simple, super lightweight library if all you want is fast, JSON-loaded tables with ajax sorting and pagination. It provides just enough to get you going and doesn't do anything fancy. It is also still very much in early development, so there are probably bugs.
4
+
5
+ ## Usage
6
+
7
+ ### Dependencies
8
+
9
+ Rails and JQuery. C'est ca. If you want to use the Javascript without Rails, feel free.
10
+
11
+ ### Install ajax_table_rails gem
12
+
13
+ Add `ajax_table_rails` to your `Gemfile` and run `bundle install`
14
+
15
+ ````
16
+ gem 'ajax_table_rails'
17
+ ````
18
+
19
+ ### Include javascript assets
20
+
21
+ Add the following to your `app/assets/javascripts/application.js`:
22
+
23
+ ````
24
+ //= require ajaxtable
25
+ ````
26
+
27
+ ### Build your table
28
+
29
+ In your view (using Users as an example):
30
+
31
+ ````
32
+ <table class="ajax-table" data-source="<%= users_path(format: :json)%>">
33
+ <thead>
34
+ <tr>
35
+ <th data-sort-column="name">Name</th>
36
+ <th data-sort-column="email">Email</th>
37
+ <th>Actions</th>
38
+ </tr>
39
+ </thead>
40
+ <tfoot>
41
+ <td colspan="3">&nbsp;</td>
42
+ </tfoot>
43
+ <tbody>
44
+ </tbody>
45
+ </table>
46
+ ````
47
+
48
+ In this example, the table will automatically initialize, and the Name and Email columns will be sortable. Record count and pagination will be inserted into the `tfoot`.
49
+
50
+ **Required attributes**
51
+
52
+ | Attribute | Description |
53
+ | --------- | ----------- |
54
+ | table data-source | JSON path for your table data |
55
+
56
+ **Optional attributes**
57
+
58
+ | Attribute | Description |
59
+ | --------- | ----------- |
60
+ | table class | "ajax-table" required for ajax tables to auto-init. Exclude this if you wish to init manually with custom settings (see below). |
61
+ | th data-sort-column | Matches database column you'd like to sort against. |
62
+
63
+ ### Customize your table
64
+
65
+ AjaxTableRails is built with Bootstrap and FontAwesome in mind, as well as some other defaults that may make you unhappy. You may want to override the classes used for pagination and sorting, as well as some other bits and bops. Here's what a full customization looks like (default values shown):
66
+
67
+ ````
68
+ $(function() {
69
+ ajaxTable.init($('#some-table'), {
70
+ cssClasses: {
71
+ count: 'at-count', // "Showing xx records out of xx" span
72
+ pagination: 'pagination', // Pagination ul, defaults to match Bootstrap
73
+ sort: 'at-sort', // Sort icon base class
74
+ sortAsc: 'fa fa-sort-up', // Sort icon ascending indicator, defaults to use FontAwesome
75
+ sortDesc: 'fa fa-sort-down' // Sort icon descending indicator, defaults to use FontAwesome
76
+ },
77
+ text: {
78
+ count: 'Showing {count} records out of {total_count}', // Pass null to skip rendering of this element
79
+ nextPage: '&raquo;',
80
+ previousPage: '&laquo;'
81
+ }
82
+ });
83
+ });
84
+ ````
85
+
86
+ ### Build your controller
87
+
88
+ Call `set_ajax_table` in a `before_action` to set your sorting criteria, then setup the query in a JSON response block.
89
+
90
+ `set_ajax_table` populates `@order` and `@page`, which you can use directly in your query. I use Kaminari for pagination, but you can use whatever you like.
91
+
92
+ ````
93
+ before_action -> {
94
+ set_ajax_table(columns: %w[name email], default_column: "name", default_direction: "desc")
95
+ }, only: [:index]
96
+
97
+ def index
98
+ respond_to do |format|
99
+ format.html {}
100
+ format.json {
101
+ @users = User.order(@order).page(@page)
102
+ }
103
+ end
104
+ end
105
+ ````
106
+
107
+ **Optional attributes**
108
+
109
+ | Attribute | Description |
110
+ | --------- | ----------- |
111
+ | columns | Whitelist of sortable columns |
112
+ | default_column | Your default sort column (if unspecified, defaults to `id`) |
113
+ | default_direction | Your default sort direction (if unspecified, deaults to `asc`) |
114
+
115
+ ### Make it shiny
116
+
117
+ Use whatever CSS you like. Here's a rudimentary example of some things you may want to do.
118
+
119
+ ````
120
+ th[data-sort-column] {
121
+ cursor: pointer;
122
+ }
123
+ i.at-sort {
124
+ margin-left: 5px;
125
+ }
126
+ span.at-count {
127
+ float: left;
128
+ margin-top: 10px;
129
+ }
130
+ ul.pagination {
131
+ float: right;
132
+ }
133
+ ````
134
+
135
+ ## Love it? Hate it?
136
+
137
+ @uberllama
138
+
139
+ I also write random [tech articles](http://blog.littleblimp.com).
140
+
141
+ ## Copyright
142
+
143
+ Copyright &copy; 2014 Yuval Kordov. See MIT-LICENSE for further details.
144
+
145
+ ## TODO
146
+
147
+ * Windowed pagination
148
+ * Result filtering
149
+ * Show default sort
150
+ * Allow customization via data attributes
data/Rakefile ADDED
@@ -0,0 +1,7 @@
1
+ begin
2
+ require 'bundler/setup'
3
+ rescue LoadError
4
+ puts 'You must `gem install bundler` and `bundle install` to run rake tasks'
5
+ end
6
+
7
+ Bundler::GemHelper.install_tasks
@@ -0,0 +1,21 @@
1
+ $:.push File.expand_path("../lib", __FILE__)
2
+
3
+ # Maintain your gem's version:
4
+ require "ajax_table_rails/version"
5
+
6
+ # Describe your gem and declare its dependencies:
7
+ Gem::Specification.new do |s|
8
+ s.name = "ajax_table_rails"
9
+ s.version = AjaxTableRails::VERSION
10
+ s.authors = ["Yuval Kordov"]
11
+ s.email = ["yuval.kordov@gmail.com"]
12
+ s.homepage = "https://github.com/uberllama/ajax_table_rails"
13
+ s.summary = "Simple JSON-loaded tables with sorting and pagination"
14
+ s.description = "An ultra lightweight alternative to datatables or dynatables, with built in Rails helpers. Still under construction [insert animated construction worker here]."
15
+ s.license = "MIT"
16
+
17
+ s.files = `git ls-files`.split("\n")
18
+ s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
19
+
20
+ s.add_dependency "rails", ">= 3.1"
21
+ end
@@ -0,0 +1,156 @@
1
+ var ajaxTable = (function($) {
2
+
3
+ // On document ready, ajaxify all tables with the `ajax-table` class.
4
+ //
5
+ // If you want to use custom settings, forego the `ajax-table` class and call init manually:
6
+ // $(function() {
7
+ // ajaxTable.init($('#some-table'), {
8
+ // cssClasses: { pagination: 'some-class' },
9
+ // text: { count: null },
10
+ // ...
11
+ // });
12
+ // });
13
+ //
14
+ // @see config Available settings
15
+ $(function() {
16
+ $('table.ajax-table').each(function() {
17
+ init($(this));
18
+ });
19
+ });
20
+
21
+ /* public */
22
+
23
+ // Load and build initial table, and bind static events
24
+ var init = function($table, options) {
25
+ $.extend(true, config, options);
26
+ $table.data('page', 1);
27
+ loadTable($table);
28
+ initSorting($table);
29
+ };
30
+
31
+ /* private */
32
+
33
+ // Default config
34
+ // All of these settings can be overriden by manually calling `init`
35
+ var config = {
36
+ // You can safely use multiple classes here
37
+ // @example `pagination: 'pagination foo-pagination'`
38
+ cssClasses: {
39
+ count: 'at-count', // "Showing xx records out of xx" span
40
+ pagination: 'pagination', // Pagination ul, defaults to match Bootstrap
41
+ sort: 'at-sort', // Sort icon base class
42
+ sortAsc: 'fa fa-sort-up', // Sort icon ascending indicator, defaults to use FontAwesome
43
+ sortDesc: 'fa fa-sort-down' // Sort icon descending indicator, defaults to use FontAwesome
44
+ },
45
+ // @note Querystring param keys match up with those used by ajax_table.rb
46
+ params: {
47
+ page: 'page',
48
+ sortColumn: 'sort',
49
+ sortDirection: 'direction'
50
+ },
51
+ // To not display count, pass `text.count: null`
52
+ text: {
53
+ count: 'Showing {count} records out of {total_count}',
54
+ nextPage: '&raquo;',
55
+ previousPage: '&laquo;'
56
+ }
57
+ };
58
+
59
+ // Load and render table, based on current sort and page
60
+ var loadTable = function($table) {
61
+ params = {};
62
+ params[config.params.page] = $table.data('page');
63
+ params[config.params.sortColumn] = $table.data('sort-column');
64
+ params[config.params.sortDirection] = $table.data('sort-direction');
65
+
66
+ var request = $.ajax({
67
+ url: $table.data('source'),
68
+ data: $.extend({ format: 'json' }, params),
69
+ type: 'GET',
70
+ dataType: 'json'
71
+ });
72
+ request.done(function(data) {
73
+ buildRows($table, data.rows);
74
+ buildPagination($table, data.pagination);
75
+ });
76
+ };
77
+
78
+ // Bind table headers to sort with direction
79
+ // @note To enable sorting on a header, add a `data-sort-column` attribute with the desired column name.
80
+ // @example `<th data-sort-column="email">Email</th>`
81
+ var initSorting = function($table) {
82
+ $table.find('th[data-sort-column]').on('click', function() {
83
+ // Set direction based on prior and clicked sort column
84
+ var sortColumn = $(this).data('sort-column');
85
+ var direction = ($table.data('sort-column') == sortColumn && $table.data('sort-direction') == 'asc') ? 'desc' : 'asc';
86
+ $table.data('sort-direction', direction);
87
+ // Set new sort column
88
+ $table.data('sort-column', sortColumn);
89
+ // Always reset page to 1 when re-sorting
90
+ $table.data('page', 1);
91
+ // Remove and re-insert sort icon
92
+ $table.find('th i.' + config.cssClasses.sort).remove();
93
+ var $i = $('<i/>', { class: config.cssClasses.sort + ' ' + (direction == 'asc' ? config.cssClasses.sortAsc : config.cssClasses.sortDesc) });
94
+ $(this).append($i);
95
+ // Reload table
96
+ loadTable($table);
97
+ });
98
+ };
99
+
100
+ // Build table rows
101
+ var buildRows = function($table, rows) {
102
+ var $tbody = $table.find('tbody');
103
+ $tbody.children().remove();
104
+ $.each(rows, function(i,row) {
105
+ var $tr = $('<tr/>');
106
+ $tbody.append($tr);
107
+ $.each(row, function(k,v) {
108
+ $tr.append('<td>' + v + '</td>');
109
+ });
110
+ });
111
+ };
112
+
113
+ // Build counts and simple pagination
114
+ var buildPagination = function($table, pagination) {
115
+ $td = $table.find('tfoot').find('td').first();
116
+ $td.children().remove();
117
+ if (pagination.total_count > pagination.count) {
118
+ // Display current out of total record count
119
+ if (config.text.count) {
120
+ var $count = $('<span/>', { class: config.cssClasses.count });
121
+ $td.append($count);
122
+ $count.html(config.text.count.replace('{count}', pagination.count).replace('{total_count}', pagination.total_count));
123
+ }
124
+ // Pagination controls
125
+ var pageCount = Math.ceil(pagination.total_count / pagination.per_page);
126
+ var currentPage = $table.data('page');
127
+ var $ul = $('<ul/>', { class: config.cssClasses.pagination });
128
+ $td.append($ul);
129
+ if (currentPage > 1) {
130
+ var previousPage = currentPage-1;
131
+ $ul.append('<li><a href="#" data-page=' + previousPage + '>' + config.text.previousPage + '</a></li>');
132
+ }
133
+ for (var pageNumber = 1; pageNumber <= pageCount; pageNumber++) {
134
+ var li = '<li';
135
+ if (pageNumber == currentPage) li += ' class="active"';
136
+ li += '>';
137
+ $ul.append(li + '<a href="#" data-page=' + pageNumber + '>' + pageNumber + '</a></li>');
138
+ }
139
+ if (currentPage < pageCount) {
140
+ var nextPage = currentPage+1;
141
+ $ul.append('<li><a href="#" data-page=' + nextPage + '>' + config.text.nextPage + '</a></li>');
142
+ }
143
+ // Bind the pagination controls
144
+ $table.find('ul.' + config.cssClasses.pagination.split(' ').join('.') + ' a').on('click', function(e) {
145
+ $table.data('page', $(this).data('page'));
146
+ loadTable($table);
147
+ e.preventDefault();
148
+ });
149
+ }
150
+ };
151
+
152
+ return {
153
+ init: init
154
+ }
155
+
156
+ })(jQuery);
@@ -0,0 +1,30 @@
1
+ module AjaxTableActions
2
+ extend ActiveSupport::Concern
3
+
4
+ private
5
+
6
+ # before_action that sets @page and @order instance variables based off ajax_table params `sort` and `direction`
7
+ #
8
+ # @example With sortable columns
9
+ # before_action -> { set_ajax_table(columns: %w[name email], default_column: "name", default_direction: "asc") }
10
+ #
11
+ # @example With no sortable columns
12
+ # before_action -> { set_ajax_table(default_column: "name", default_direction: "asc") }
13
+ #
14
+ # @param [Hash] options Optional configuration. If none specified, sort params are ignored and the collection is sorted by ID
15
+ # @option options [Array] columns Whitelisted columns that can be sorted on
16
+ # @option options [String] default_column Default sort column
17
+ # @option options [String] default_direction Default sort direction
18
+ def set_ajax_table(options = {})
19
+ @page = [params[:page].to_i, 1].max
20
+
21
+ unless options.empty?
22
+ column = (options[:columns] && options[:columns].detect {|column| column == params[:sort]}) || options[:default_column]
23
+ direction = %w[asc desc].include?(params[:direction]) ? params[:direction] : options[:default_direction]
24
+ end
25
+ column ||= 'id'
26
+ direction ||= 'asc'
27
+ @order = "#{column} #{direction}"
28
+ end
29
+
30
+ end
@@ -0,0 +1,9 @@
1
+ module AjaxTableRails
2
+ class Engine < ::Rails::Engine
3
+ initializer "ajax_table_rails.load_before_actions" do
4
+ ActiveSupport.on_load(:action_controller) do
5
+ ActionController::Base.send(:include, AjaxTableActions)
6
+ end
7
+ end
8
+ end
9
+ end
@@ -0,0 +1,3 @@
1
+ module AjaxTableRails
2
+ VERSION = "0.0.1"
3
+ end
@@ -0,0 +1,4 @@
1
+ require "ajax_table_rails/engine"
2
+
3
+ module AjaxTableRails
4
+ end
metadata ADDED
@@ -0,0 +1,72 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: ajax_table_rails
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.1
5
+ platform: ruby
6
+ authors:
7
+ - Yuval Kordov
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2014-01-28 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: rails
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '3.1'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '3.1'
27
+ description: An ultra lightweight alternative to datatables or dynatables, with built
28
+ in Rails helpers. Still under construction [insert animated construction worker
29
+ here].
30
+ email:
31
+ - yuval.kordov@gmail.com
32
+ executables: []
33
+ extensions: []
34
+ extra_rdoc_files: []
35
+ files:
36
+ - ".gitignore"
37
+ - CHANGELOG.md
38
+ - Gemfile
39
+ - MIT-LICENSE
40
+ - README.md
41
+ - Rakefile
42
+ - ajax_table_rails.gemspec
43
+ - app/assets/javascripts/ajaxtable.js
44
+ - app/controllers/concerns/ajax_table_actions.rb
45
+ - lib/ajax_table_rails.rb
46
+ - lib/ajax_table_rails/engine.rb
47
+ - lib/ajax_table_rails/version.rb
48
+ homepage: https://github.com/uberllama/ajax_table_rails
49
+ licenses:
50
+ - MIT
51
+ metadata: {}
52
+ post_install_message:
53
+ rdoc_options: []
54
+ require_paths:
55
+ - lib
56
+ required_ruby_version: !ruby/object:Gem::Requirement
57
+ requirements:
58
+ - - ">="
59
+ - !ruby/object:Gem::Version
60
+ version: '0'
61
+ required_rubygems_version: !ruby/object:Gem::Requirement
62
+ requirements:
63
+ - - ">="
64
+ - !ruby/object:Gem::Version
65
+ version: '0'
66
+ requirements: []
67
+ rubyforge_project:
68
+ rubygems_version: 2.2.1
69
+ signing_key:
70
+ specification_version: 4
71
+ summary: Simple JSON-loaded tables with sorting and pagination
72
+ test_files: []