data_tables-responder 0.2.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: 499aade7583b2148751f39d6004c1b3bea164620
4
+ data.tar.gz: 502c2d8e2aa857390f3e55c8139204d375670032
5
+ SHA512:
6
+ metadata.gz: 71c654d1f58279888be4541f919e4ce8b51f1c7da354b4d4b9a04ee5eacb6be6844cd87e6857711e7b8c9a7341ba94f0cc4910afdcd57e428f40897a8878117b
7
+ data.tar.gz: d938cf9b87575b5d2a18dbf0dacb315e1fa7e286bf1f5cc37bbb228bbe1e0f7da89f59d653d730bd0f5d87ec3da49878b367dfeb506946558aacb449353a30df
data/.gitignore ADDED
@@ -0,0 +1,9 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /Gemfile.lock
4
+ /_yardoc/
5
+ /coverage/
6
+ /doc/
7
+ /pkg/
8
+ /spec/reports/
9
+ /tmp/
data/.rspec ADDED
@@ -0,0 +1,2 @@
1
+ --format documentation
2
+ --color
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in data_tables-responder.gemspec
4
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2016 Dale Stevens
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,64 @@
1
+ # DataTables::Responder
2
+
3
+ DataTables Responder assists with responding, filtering, searching, paginating and formatting results from DataTable client requests.
4
+
5
+ ## Installation
6
+
7
+ Add this line to your application's Gemfile:
8
+
9
+ ```ruby
10
+ gem 'data_tables-responder'
11
+ ```
12
+
13
+ And then execute:
14
+
15
+ $ bundle
16
+
17
+ Or install it yourself as:
18
+
19
+ $ gem install data_tables-responder
20
+
21
+ ## Usage
22
+
23
+ ```ruby
24
+ # routes.rb
25
+
26
+ resources :users do
27
+ post :index, constraints: { format: :dt }, on: :collection
28
+ end
29
+ ```
30
+
31
+ ```ruby
32
+ class UsersController < ApplicationController
33
+
34
+ def index
35
+ @users = User.all
36
+ respond_to do |format|
37
+ format.dt { render json: @users, adapter: DataTables::Adapter }
38
+ end
39
+ end
40
+
41
+ # ...
42
+
43
+ end
44
+ ```
45
+
46
+ ## Roadmap
47
+
48
+ * Adapters for popular Search and Pagination gems
49
+
50
+ ## Development
51
+
52
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
53
+
54
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
55
+
56
+ ## Contributing
57
+
58
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/data_tables-responder.
59
+
60
+
61
+ ## License
62
+
63
+ The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
64
+
data/Rakefile ADDED
@@ -0,0 +1,6 @@
1
+ require "bundler/gem_tasks"
2
+ require "rspec/core/rake_task"
3
+
4
+ RSpec::Core::RakeTask.new(:spec)
5
+
6
+ task :default => :spec
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "data_tables/responder"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,34 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'data_tables/responder/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = 'data_tables-responder'
8
+ spec.version = DataTables::Responder::VERSION
9
+ spec.authors = ['Dale Stevens']
10
+ spec.email = ['dale@twilightcoders.net']
11
+
12
+ spec.summary = 'Respond to DataTable requests.'
13
+ spec.homepage = "https://github.com/TwilightCoders/data_tables-responder"
14
+ spec.license = 'MIT'
15
+
16
+ # Prevent pushing this gem to RubyGems.org. To allow pushes either set the 'allowed_push_host'
17
+ # to allow pushing to a single host or delete this section to allow pushing to any host.
18
+ if spec.respond_to?(:metadata)
19
+ spec.metadata['allowed_push_host'] = 'https://rubygems.org'
20
+ else
21
+ raise 'RubyGems 2.0 or newer is required to protect against public gem pushes.'
22
+ end
23
+
24
+ spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
25
+ spec.bindir = 'exe'
26
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
27
+ spec.require_paths = ['lib']
28
+
29
+ spec.add_dependency 'active_model_serializers', '~> 0.10.0'
30
+
31
+ spec.add_development_dependency 'bundler', '~> 1.12'
32
+ spec.add_development_dependency 'rake', '~> 10.0'
33
+ spec.add_development_dependency 'rspec', '~> 3.0'
34
+ end
@@ -0,0 +1,99 @@
1
+ require 'active_model_serializers'
2
+ require 'data_tables/modules/pagination'
3
+ require 'data_tables/modules/search'
4
+
5
+ module DataTables
6
+ def self.flat_keys_to_nested(hash)
7
+ hash.each_with_object({}) do |(key, value), all|
8
+ key_parts = key.split('.').map!(&:to_sym)
9
+ leaf = key_parts[0...-1].inject(all) { |h, k| h[k] ||= {} }
10
+ leaf[key_parts.last] = value
11
+ end
12
+ end
13
+
14
+ class Adapter < ::ActiveModelSerializers::Adapter::Base
15
+
16
+ def serializable_hash(options)
17
+ options = serialization_options(options)
18
+ @serialization_context = options[:serialization_context]
19
+
20
+ collection = serializer.object
21
+
22
+ params = @serialization_context.request_parameters
23
+ model = collection.try(:model) || collection
24
+
25
+ @results = collection
26
+ hashed_orders = transmute_datatable_order(params[:order], params[:columns])
27
+ orders = DataTables.flat_keys_to_nested hashed_orders
28
+
29
+ order_by = orders.collect do |k, order|
30
+ if order.is_a? Hash
31
+ if (klass = model.reflect_on_association(k).try(:klass))
32
+ @results = @results.joins(k)
33
+ klass.arel_table[order.first.first].send(order.first.last)
34
+ end
35
+ else
36
+ { k => order }
37
+ end
38
+ end
39
+
40
+ @results = search(@results)
41
+
42
+ # Rails.logger.warn "SEARCH BY: #{search_by}"
43
+ @results = order_by.inject(@results) { |r, o| r.order(o) }
44
+ @results = paginate(@results)
45
+
46
+ new_serializer = serializer.class.new(@results, serializer.instance_variable_get(:@options))
47
+ serialized_hash = {
48
+ data: ::ActiveModelSerializers::Adapter::Attributes.new(new_serializer, instance_options).serializable_hash(options)
49
+ }
50
+ serialized_hash[meta_key] = meta unless meta.blank?
51
+ serialized_hash.merge!(@pagination.as_json) unless @pagination.blank?
52
+
53
+ self.class.transform_key_casing!(serialized_hash, instance_options)
54
+ # binding.pry
55
+ end
56
+
57
+ def reformatted_columns(params)
58
+ # binding.pry
59
+ params[:columns]
60
+ end
61
+
62
+ protected
63
+
64
+ def paginate(collection)
65
+ @pagination ||= Modules::Pagination.new(collection, instance_options)
66
+ collection = @pagination.paginate
67
+ end
68
+
69
+ def search(collection)
70
+ @search ||= Modules::Search.new(collection, instance_options)
71
+ collection = @search.search
72
+ end
73
+
74
+ def transmute_datatable_order(orders, columns)
75
+ Hash[if orders.is_a? Array
76
+ orders.collect do |order|
77
+ if (name = columns[order[:column]][:data]).present?
78
+ [name, order[:dir]]
79
+ else
80
+ nil
81
+ end
82
+ end
83
+ else
84
+ []
85
+ end.compact]
86
+ end
87
+
88
+ def meta
89
+ {
90
+ sql: @results.to_sql
91
+ }.merge(instance_options.fetch(:meta, {}))
92
+ end
93
+
94
+ def meta_key
95
+ instance_options.fetch(:meta_key, 'meta'.freeze)
96
+ end
97
+
98
+ end
99
+ end
@@ -0,0 +1,46 @@
1
+ module DataTables
2
+ module Modules
3
+ class Pagination
4
+ MissingSerializationContextError = Class.new(KeyError)
5
+ FIRST_PAGE = 1
6
+
7
+ attr_reader :collection, :context
8
+
9
+ def initialize(collection, adapter_options)
10
+ @collection = collection
11
+ @adapter_options = adapter_options
12
+ @context = adapter_options.fetch(:serialization_context) do
13
+ fail MissingSerializationContextError, <<-EOF.freeze
14
+ Datatables::Pagination requires a ActiveModelSerializers::SerializationContext.
15
+ Please pass a ':serialization_context' option or
16
+ override CollectionSerializer#paginated? to return 'false'.
17
+ EOF
18
+ end
19
+ end
20
+
21
+ def paginate
22
+ start = (request_parameters[:start] || '0').to_i
23
+ length = (request_parameters[:length] || '10').to_i
24
+ page = (start / length) + 1
25
+ @collection = @collection.paginate(page: page, per_page: length)
26
+ end
27
+
28
+ def as_json
29
+ {
30
+ recordsTotal: @collection&.model&.count || 0,
31
+ recordsFiltered: @collection&.total_entries || 0
32
+ }
33
+ end
34
+
35
+ protected
36
+
37
+ attr_reader :adapter_options
38
+
39
+ private
40
+
41
+ def request_parameters
42
+ @request_parameters ||= context.request_parameters
43
+ end
44
+ end
45
+ end
46
+ end
@@ -0,0 +1,84 @@
1
+ module DataTables
2
+ module Modules
3
+ class Search
4
+ MissingSerializationContextError = Class.new(KeyError)
5
+
6
+ attr_reader :collection, :context
7
+
8
+ def initialize(collection, adapter_options)
9
+ @collection = collection
10
+ @adapter_options = adapter_options
11
+ @context = adapter_options.fetch(:serialization_context) do
12
+ fail MissingSerializationContextError, <<-EOF.freeze
13
+ Datatables::Search requires a ActiveModelSerializers::SerializationContext.
14
+ Please pass a ':serialization_context' option or
15
+ override CollectionSerializer#searchable? to return 'false'.
16
+ EOF
17
+ end
18
+ end
19
+
20
+ def search
21
+ default_search = request_parameters.dig(:search, :value)
22
+
23
+ model = @collection.try(:model) || @collection
24
+ arel_table = model.arel_table
25
+ columns = searchable_columns(default_search)
26
+
27
+ searches = DataTables.flat_keys_to_nested columns
28
+
29
+ or_clause = nil
30
+ search_by = searches.collect do |k, query|
31
+ if query.is_a? Hash
32
+ assoc = model.reflect_on_association(k)
33
+ assoc_klass = assoc.klass
34
+ assoc_arel_table = assoc_klass.arel_table
35
+
36
+ if model.respond_to? :left_outer_join
37
+ @collection = @collection.left_outer_join(k)
38
+ else
39
+ @collection = @collection.includes(k).references(k)
40
+ end
41
+
42
+ assoc_arel_table[query.first.first].matches(query.first.last)
43
+ else
44
+ if (column = model.columns.find { |c| c.name == k.to_s })
45
+ case column.type
46
+ when :string
47
+ model.arel_table[k].matches("%#{query}%")
48
+ when :integer
49
+ model.arel_table[k].eq(query)
50
+ else
51
+ nil
52
+ end
53
+ end
54
+ end
55
+ end.compact
56
+
57
+ @collection.where(search_by.reduce(:or))
58
+ end
59
+
60
+ protected
61
+
62
+ def searchable_columns(default_search)
63
+ @searchable_columns = {}
64
+ request_parameters[:columns]&.inject(@searchable_columns) do |a, b|
65
+ if (b[:searchable] && b[:data].present?)
66
+ if ((value = b.dig(:search, :value).present? ? b.dig(:search, :value) : default_search).present?)
67
+ a[b[:data]] = value
68
+ end
69
+ end
70
+ a
71
+ end
72
+
73
+ @searchable_columns
74
+ end
75
+
76
+ private
77
+
78
+ def request_parameters
79
+ @request_parameters ||= context.request_parameters
80
+ end
81
+
82
+ end
83
+ end
84
+ end
@@ -0,0 +1,21 @@
1
+ require 'active_model_serializers/serialization_context'
2
+ module ActiveModelSerializers
3
+ class SerializationContext
4
+ attr_reader :request_parameters
5
+
6
+ def initialize(*args)
7
+ options = args.extract_options!
8
+ if args.size == 1
9
+ request = args.pop
10
+ options[:request_url] = request.original_url[/\A[^?]+/]
11
+ options[:query_parameters] = request.query_parameters
12
+ options[:request_parameters] = request.request_parameters
13
+ end
14
+ @request_url = options.delete(:request_url)
15
+ @query_parameters = options.delete(:query_parameters)
16
+ @request_parameters = options.delete(:request_parameters)
17
+ @url_helpers = options.delete(:url_helpers) || self.class.url_helpers
18
+ @default_url_options = options.delete(:default_url_options) || self.class.default_url_options
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,11 @@
1
+ require 'rails'
2
+
3
+ module DataTables
4
+ module Responder
5
+ class Railtie < ::Rails::Railtie
6
+ initializer "data_tables.configure", after: 'active_model_serializers.prepare_serialization_context' do
7
+ Mime::Type.register_alias 'application/json', :dt, %w( text/plain text/x-json application/jsonrequest application/dt application/datatable )
8
+ end
9
+ end
10
+ end
11
+ end
@@ -0,0 +1,5 @@
1
+ module DataTables
2
+ module Responder
3
+ VERSION = '0.2.1'
4
+ end
5
+ end
@@ -0,0 +1,11 @@
1
+ require "data_tables/responder/version"
2
+ # Monkey-patch :/
3
+ require "data_tables/monkey_patch/active_model_serializers/serialization_context"
4
+
5
+ require 'data_tables/adapter'
6
+ require 'data_tables/responder/railtie' if defined? ::Rails::Railtie
7
+
8
+ module DataTables
9
+ module Responder
10
+ end
11
+ end
metadata ADDED
@@ -0,0 +1,117 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: data_tables-responder
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.2.1
5
+ platform: ruby
6
+ authors:
7
+ - Dale Stevens
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2017-01-06 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: active_model_serializers
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: 0.10.0
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: 0.10.0
27
+ - !ruby/object:Gem::Dependency
28
+ name: bundler
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '1.12'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '1.12'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rake
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '10.0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '10.0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: rspec
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: '3.0'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: '3.0'
69
+ description:
70
+ email:
71
+ - dale@twilightcoders.net
72
+ executables: []
73
+ extensions: []
74
+ extra_rdoc_files: []
75
+ files:
76
+ - ".gitignore"
77
+ - ".rspec"
78
+ - Gemfile
79
+ - LICENSE.txt
80
+ - README.md
81
+ - Rakefile
82
+ - bin/console
83
+ - bin/setup
84
+ - data_tables-responder.gemspec
85
+ - lib/data_tables-responder.rb
86
+ - lib/data_tables/adapter.rb
87
+ - lib/data_tables/modules/pagination.rb
88
+ - lib/data_tables/modules/search.rb
89
+ - lib/data_tables/monkey_patch/active_model_serializers/serialization_context.rb
90
+ - lib/data_tables/responder/railtie.rb
91
+ - lib/data_tables/responder/version.rb
92
+ homepage: https://github.com/TwilightCoders/data_tables-responder
93
+ licenses:
94
+ - MIT
95
+ metadata:
96
+ allowed_push_host: https://rubygems.org
97
+ post_install_message:
98
+ rdoc_options: []
99
+ require_paths:
100
+ - lib
101
+ required_ruby_version: !ruby/object:Gem::Requirement
102
+ requirements:
103
+ - - ">="
104
+ - !ruby/object:Gem::Version
105
+ version: '0'
106
+ required_rubygems_version: !ruby/object:Gem::Requirement
107
+ requirements:
108
+ - - ">="
109
+ - !ruby/object:Gem::Version
110
+ version: '0'
111
+ requirements: []
112
+ rubyforge_project:
113
+ rubygems_version: 2.5.1
114
+ signing_key:
115
+ specification_version: 4
116
+ summary: Respond to DataTable requests.
117
+ test_files: []