pager_api 0.1.0

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: e79547244421e6ea67f19bdd6b4190b6b6e6086f
4
+ data.tar.gz: 0021669263b8652f59664122742e7469b94eedd1
5
+ SHA512:
6
+ metadata.gz: c80c5b7ddfe46f0735df8ae3aa7522b3742f0750b7dd1777eaf6ede8db8abe7791c6192db1b407121048802eeacdafecb9c405500806afff1d6194c38fa6d2c7
7
+ data.tar.gz: cc86e17bdf752e4e496596c69d38c310f054d500b2a3f91aac7763814fc557536297bdc29b59270b87f7bbf1a55bc5a57c9af6506093970ecbd9533e969ca02f
data/.gitignore ADDED
@@ -0,0 +1,10 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /Gemfile.lock
4
+ /_yardoc/
5
+ /coverage/
6
+ /doc/
7
+ /pkg/
8
+ /spec/reports/
9
+ /tmp/
10
+ .DS_Store
data/.rspec ADDED
@@ -0,0 +1,2 @@
1
+ --format documentation
2
+ --color
data/.travis.yml ADDED
@@ -0,0 +1,3 @@
1
+ language: ruby
2
+ rvm:
3
+ - 2.2.1
@@ -0,0 +1,13 @@
1
+ # Contributor Code of Conduct
2
+
3
+ As contributors and maintainers of this project, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities.
4
+
5
+ We are committed to making participation in this project a harassment-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, age, or religion.
6
+
7
+ Examples of unacceptable behavior by participants include the use of sexual language or imagery, derogatory comments or personal attacks, trolling, public or private harassment, insults, or other unprofessional conduct.
8
+
9
+ Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct. Project maintainers who do not follow the Code of Conduct may be removed from the project team.
10
+
11
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by opening an issue or contacting one or more of the project maintainers.
12
+
13
+ This Code of Conduct is adapted from the [Contributor Covenant](http:contributor-covenant.org), version 1.0.0, available at [http://contributor-covenant.org/version/1/0/0/](http://contributor-covenant.org/version/1/0/0/)
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in pager_api.gemspec
4
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2015 Abraham Kuri
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,136 @@
1
+ # Pager API
2
+
3
+ ![Pager](http://iplp.com/pagers/images/448/Gold+Alphanumeric+Pager+-+2871+-+3+-+400.jpg)
4
+
5
+ API Pagination made it right. Pager API is a library to help you add `meta` information and the adecuate header with pagination information based on the [JSON API standard](http://jsonapi.org) for your Rails app.
6
+
7
+ ## Table of contents
8
+ - [Quick start](#quick-start)
9
+ - [Configuration](#configuration)
10
+ - [Usage](#usage)
11
+ - [Bug tracker & feature request](#bug-tracker-&-feature-request)
12
+ - [Documentation or Installation instructions](#documentation)
13
+ - [Contributing](#contributing)
14
+ - [Community](#community)
15
+ - [Heroes](#heroes)
16
+ - [License](#license)
17
+
18
+
19
+ ## Quick Start
20
+
21
+ `pager_api` depends on [Kaminari](https://github.com/amatsuda/kaminari) or [WillPaginate](https://github.com/mislav/will_paginate) to handle pagination. You need to add one of these to your Gemfile:
22
+
23
+ ```ruby
24
+ # gem 'will_paginate'
25
+ # gem 'kaminari'
26
+ gem 'pager_api'
27
+ ```
28
+
29
+ And then execute:
30
+
31
+ ```console
32
+ % bundle
33
+ ```
34
+
35
+ ## Configuration
36
+
37
+ **This step is totally optional**
38
+
39
+ The gem comes with an installer for you to configure it, for example to switch between pagination handlers or whether or not to include the `Link` header or meta information. To install it you just need to run:
40
+
41
+ ```console
42
+ % rails g pager_api:install
43
+ ```
44
+
45
+ This will create a file under the `initializers` directory called `pager_api.rb`. You can easily configure it there to meet your needs.
46
+
47
+ By default `pager_api` uses [Kaminari](https://github.com/amatsuda/kaminari).
48
+
49
+ ## Usage
50
+
51
+ On your controller where you are providing a paginated collection, where you may have something like:
52
+
53
+ ```ruby
54
+ class UsersController < ApplicationController
55
+
56
+ def index
57
+ users = User.page(params[:page]).per(15)
58
+ render json: users, meta: { pagination: {
59
+ per_page: 15,
60
+ total_pages: 10,
61
+ total_objects: 150
62
+ } }
63
+ end
64
+ end
65
+ ```
66
+
67
+ With `pager_api` is really easy to achieve just by:
68
+
69
+ ```ruby
70
+ class UsersController < ApplicationController
71
+
72
+ def index
73
+ # You can have any scope for the User class in this case
74
+ # You can even send the paginated collection
75
+ paginate User.unscoped, per_page: 15
76
+ end
77
+ end
78
+ ```
79
+
80
+ This will output a json object like:
81
+
82
+ ```json
83
+ {
84
+ "users": [
85
+ ...
86
+ ],
87
+ "meta": {
88
+ "pagination": {
89
+ "per_page": 15,
90
+ "total_pages": 1,
91
+ "total_objects": 15,
92
+ "links": {
93
+ "first": "/api/users?page=1",
94
+ "last": "/api/users?page=1"
95
+ }
96
+ }
97
+ }
98
+ }
99
+ ```
100
+
101
+ As you can see, the pagination metadata also includes the links information for the `first` and `last` page, but it will also create the `next` and the `prev` keys when necessary.
102
+
103
+ By default it will also include a `Link` header with the following information:
104
+
105
+ ```
106
+ # Link: <http://example.com/api/v1/users?page="2">; rel="next",
107
+ # <http://example.com/api/v1//users?page="5">; rel="last",
108
+ # <http://example.com/api/v1//users?page="1">; rel="first",
109
+ # <http://example.com/api/v1/users?page="1">; rel="prev",
110
+ ```
111
+
112
+ The header will be created with the corresponding `first`, `last`, `prev` and `next`.
113
+
114
+ ## Bug tracker & feature request
115
+
116
+ Have a bug or a feature request? [Please open a new issue](https://github.com/IcaliaLabs/pager-api/issues). Before opening any issue, please search for existing issues.
117
+
118
+ ## Contributing
119
+
120
+ Please submit all pull requests against a separate branch. Although it does not have tests yet, be a nice guy and add some for your feature. We'll be working hard to add them too.
121
+
122
+ In case you are wondering what to attack, we have a milestone with the version to work, some fixes and refactors. Feel free to start one.
123
+
124
+ Thanks!
125
+
126
+ ## Heroes
127
+
128
+ **Abraham Kuri**
129
+
130
+ + [http://twitter.com/kurenn](http://twitter.com/kurenn)
131
+ + [http://github.com/kurenn](http://github.com/kurenn)
132
+ + [http://klout.com/#/kurenn](http://klout.com/#/kurenn)
133
+
134
+ ## License
135
+
136
+ Code and documentation copyright 2015 Icalia Labs. Code released under [the MIT license](LICENSE).
data/Rakefile ADDED
@@ -0,0 +1 @@
1
+ require "bundler/gem_tasks"
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "pager_api"
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,7 @@
1
+ #!/bin/bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+
5
+ bundle install
6
+
7
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,13 @@
1
+ module PagerApi
2
+ module Generators
3
+ class InstallGenerator < Rails::Generators::Base
4
+ source_root File.expand_path("../templates", __FILE__)
5
+
6
+ desc "Creates a PagerApi initializer in your application"
7
+
8
+ def copy_initializer
9
+ template "pager_api.rb", "config/initializers/pager_api.rb"
10
+ end
11
+ end
12
+ end
13
+ end
@@ -0,0 +1,21 @@
1
+ # Use this module to configure pager the available options
2
+ #
3
+ # Made with love by @icalialabs
4
+
5
+ PagerApi.setup do |config|
6
+
7
+ # Pagination Handler
8
+ # User this option to meet your pagination handler, whether is :kaminari or :will_paginate
9
+ # config.pagination_handler = :kaminari
10
+
11
+ # Includes Pagination information on Meta
12
+ #
13
+ # config.include_pagination_on_meta = true
14
+
15
+ # Includes Pagination information on a Link Header
16
+ #
17
+ # config.include_pagination_headers = true
18
+
19
+ # Set the Total-Count Header name
20
+ # config.total_count_header = "X-Total-Count"
21
+ end
@@ -0,0 +1,16 @@
1
+ # Dynamic pagination handler call
2
+ require "pager_api/pagination/#{PagerApi.pagination_handler}"
3
+
4
+ begin; require 'kaminari'; rescue LoadError; end
5
+ begin; require 'will_paginate'; rescue LoadError; end
6
+
7
+ ActionController::Base.send(:include, "PagerApi::Pagination::#{PagerApi.pagination_handler.to_s.classify}".constantize)
8
+
9
+ unless defined?(Kaminari) or defined?(WillPaginate)
10
+ Kernel.warn <<-WARNING.gsub(/^\s{4}/, '')
11
+ Warning: pager-api needs Kaminari or Will Paginate as a dependency.
12
+ You need to add it to your Gemfile
13
+
14
+ gem 'kaminari' or gem 'will_paginate'
15
+ WARNING
16
+ end
@@ -0,0 +1,87 @@
1
+ require 'pry'
2
+ module PagerApi
3
+ module Pagination
4
+ module Kaminari
5
+
6
+ def paginate(*args)
7
+ options = args.extract_options!
8
+ collection = args.first
9
+
10
+ paginated_collection = paginate_collection(collection, options)
11
+
12
+ options[:json] = paginated_collection
13
+
14
+ options[:meta] = meta(paginated_collection, options) if PagerApi.include_pagination_on_meta?
15
+
16
+ pagination_headers(paginated_collection) if PagerApi.include_pagination_headers?
17
+
18
+ render options
19
+ end
20
+
21
+ private
22
+
23
+ # Link: <http://example.com/api/v1/users?page="2">; rel="next",
24
+ # <http://example.com/api/v1//users?page="5">; rel="last",
25
+ # <http://example.com/api/v1//users?page="1">; rel="first",
26
+ # <http://example.com/api/v1/users?page="1">; rel="prev",
27
+ def pagination_headers(collection)
28
+ links = (headers['Link'] || "").split(',').map(&:strip)
29
+ clean_url = request.original_url.sub(/\?.*$/, '')
30
+
31
+ paging_info = pages(collection)
32
+
33
+ paging_info.each do |key, value|
34
+ query_params = request.query_parameters.merge(page: value)
35
+ links << %Q( <#{clean_url}?#{query_params.to_param}>; rel="#{key}" )
36
+ end
37
+
38
+ headers['Link'] = links.join(", ") unless links.empty?
39
+ headers[PagerApi.total_count_header] = collection.total_pages
40
+
41
+ return nil
42
+ end
43
+
44
+ def pagination_links(collection)
45
+ current_uri = request.env['PATH_INFO']
46
+ meta_links = {}
47
+
48
+ pages(collection).each do |key, value|
49
+ query_params = request.query_parameters.merge(page: value)
50
+ meta_links[key] = "#{current_uri}?#{query_params.to_param}"
51
+ end
52
+
53
+ meta_links
54
+ end
55
+
56
+ def pages(collection)
57
+ {}.tap do |paging|
58
+ paging[:first] = 1
59
+ paging[:last] = collection.total_pages
60
+
61
+ paging[:prev] = collection.current_page - 1 unless collection.first_page?
62
+ paging[:next] = collection.current_page + 1 unless collection.last_page? or collection.current_page >= collection.total_pages
63
+ end
64
+ end
65
+
66
+ def paginate_collection(collection, options = {})
67
+ options[:page] = params[:page] || 1
68
+ options[:per_page] = options.delete(:per_page) || params[:per_page]
69
+
70
+ collection.page(options[:page]).per(options[:per_page])
71
+ end
72
+
73
+ def meta(collection, options = {})
74
+ {
75
+ pagination:
76
+ {
77
+ per_page: options[:per_page].to_i || params[:per_page].to_i || ::Kaminari.config.default_per_page,
78
+ total_pages: collection.total_pages,
79
+ total_objects: collection.total_count,
80
+ links: pagination_links(collection)
81
+ }
82
+ }
83
+ end
84
+
85
+ end
86
+ end
87
+ end
@@ -0,0 +1,85 @@
1
+ module PagerApi
2
+ module Pagination
3
+ module WillPaginate
4
+
5
+ def paginate(*args)
6
+ options = args.extract_options!
7
+ collection = args.first
8
+
9
+ paginated_collection = paginate_collection(collection, options)
10
+
11
+ options[:json] = paginated_collection
12
+
13
+ options[:meta] = meta(paginated_collection, options) if PagerApi.include_pagination_on_meta?
14
+
15
+ pagination_headers(paginated_collection) if PagerApi.include_pagination_headers?
16
+
17
+ render options
18
+ end
19
+
20
+ private
21
+
22
+ # Link: <http://example.com/api/v1/users?page="2">; rel="next",
23
+ # <http://example.com/api/v1//users?page="5">; rel="last",
24
+ # <http://example.com/api/v1//users?page="1">; rel="first",
25
+ # <http://example.com/api/v1/users?page="1">; rel="prev",
26
+ def pagination_headers(collection)
27
+ links = (headers['Link'] || "").split(',').map(&:strip)
28
+ clean_url = request.original_url.sub(/\?.*$/, '')
29
+
30
+ paging_info = pages(collection)
31
+
32
+ paging_info.each do |key, value|
33
+ query_params = request.query_parameters.merge(page: value)
34
+ links << %Q( <#{clean_url}?#{query_params.to_param}>; rel="#{key}" )
35
+ end
36
+
37
+ headers['Link'] = links.join(", ") unless links.empty?
38
+ headers[PagerApi.total_count_header] = collection.total_pages
39
+
40
+ return nil
41
+ end
42
+
43
+ def pagination_links(collection)
44
+ current_uri = request.env['PATH_INFO']
45
+ meta_links = {}
46
+
47
+ pages(collection).each do |key, value|
48
+ query_params = request.query_parameters.merge(page: value)
49
+ meta_links[key] = "#{current_uri}?#{query_params.to_param}"
50
+ end
51
+
52
+ meta_links
53
+ end
54
+
55
+ def pages(collection)
56
+ {}.tap do |paging|
57
+ paging[:first] = 1
58
+ paging[:last] = collection.total_pages
59
+
60
+ paging[:prev] = collection.current_page - 1 unless collection.current_page == 1
61
+ paging[:next] = collection.current_page + 1 unless collection.current_page >= collection.total_pages
62
+ end
63
+ end
64
+
65
+ def paginate_collection(collection, options = {})
66
+ options[:page] = params[:page] || 1
67
+ options[:per_page] = options.delete(:per_page) || params[:per_page]
68
+
69
+ collection.paginate(options)
70
+ end
71
+
72
+ def meta(collection, options = {})
73
+ {
74
+ pagination:
75
+ {
76
+ per_page: options[:per_page] || params[:per_page] || ::WillPaginate.per_page,
77
+ total_pages: collection.total_pages,
78
+ total_objects: collection.total_entries,
79
+ links: pagination_links(collection)
80
+ }
81
+ }
82
+ end
83
+ end
84
+ end
85
+ end
@@ -0,0 +1,11 @@
1
+ module PagerApi
2
+ class Railtie < Rails::Railtie
3
+
4
+ initializer "pager_api.action_dispatch" do |app|
5
+ ActiveSupport.on_load :action_controller do
6
+ require "pager_api/hooks"
7
+ end
8
+ end
9
+
10
+ end
11
+ end
@@ -0,0 +1,3 @@
1
+ module PagerApi
2
+ VERSION = "0.1.0"
3
+ end
data/lib/pager_api.rb ADDED
@@ -0,0 +1,35 @@
1
+ module PagerApi
2
+
3
+ # pagination handler
4
+ mattr_accessor :pagination_handler
5
+ @@pagination_handler = :kaminari
6
+
7
+ # Meta tag information for pagination
8
+ mattr_accessor :include_pagination_on_meta
9
+ @@include_pagination_on_meta = true
10
+
11
+ # Links headeras with pagination information
12
+ mattr_accessor :include_pagination_headers
13
+ @@include_pagination_headers = true
14
+
15
+ # Total Count Header name
16
+ mattr_accessor :total_count_header
17
+ @@total_count_header = "X-Total-Count"
18
+
19
+ def self.include_pagination_on_meta?
20
+ @@include_pagination_on_meta
21
+ end
22
+
23
+ def self.include_pagination_headers?
24
+ @@include_pagination_headers
25
+ end
26
+
27
+ #Method to configure pager api
28
+ def self.setup
29
+ yield self
30
+ end
31
+
32
+ end
33
+
34
+ require "pager_api/version"
35
+ require "pager_api/railtie"
data/pager_api.gemspec ADDED
@@ -0,0 +1,24 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'pager_api/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "pager_api"
8
+ spec.version = PagerApi::VERSION
9
+ spec.authors = ["Abraham Kuri"]
10
+ spec.email = ["kurenn@icalialabs.com"]
11
+
12
+ spec.summary = %q{A Rails pagination JSON handler, perfect for API}
13
+ spec.description = %q{A super simple yet powerful gem to respond with paginated collections using the JSON API standard}
14
+ spec.homepage = "https://github.com/IcaliaLabs/pager-api"
15
+ spec.license = "MIT"
16
+
17
+ spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
18
+ spec.bindir = "exe"
19
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
20
+ spec.require_paths = ["lib"]
21
+
22
+ spec.add_development_dependency "bundler", "~> 1.9"
23
+ spec.add_development_dependency "rake", "~> 10.0"
24
+ end
metadata ADDED
@@ -0,0 +1,93 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: pager_api
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Abraham Kuri
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2015-08-03 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: bundler
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '1.9'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.9'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rake
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '10.0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '10.0'
41
+ description: A super simple yet powerful gem to respond with paginated collections
42
+ using the JSON API standard
43
+ email:
44
+ - kurenn@icalialabs.com
45
+ executables: []
46
+ extensions: []
47
+ extra_rdoc_files: []
48
+ files:
49
+ - ".gitignore"
50
+ - ".rspec"
51
+ - ".travis.yml"
52
+ - CODE_OF_CONDUCT.md
53
+ - Gemfile
54
+ - LICENSE.txt
55
+ - README.md
56
+ - Rakefile
57
+ - bin/console
58
+ - bin/setup
59
+ - lib/generators/pager_api/install_generator.rb
60
+ - lib/generators/pager_api/templates/pager_api.rb
61
+ - lib/pager_api.rb
62
+ - lib/pager_api/hooks.rb
63
+ - lib/pager_api/pagination/kaminari.rb
64
+ - lib/pager_api/pagination/will_paginate.rb
65
+ - lib/pager_api/railtie.rb
66
+ - lib/pager_api/version.rb
67
+ - pager_api.gemspec
68
+ homepage: https://github.com/IcaliaLabs/pager-api
69
+ licenses:
70
+ - MIT
71
+ metadata: {}
72
+ post_install_message:
73
+ rdoc_options: []
74
+ require_paths:
75
+ - lib
76
+ required_ruby_version: !ruby/object:Gem::Requirement
77
+ requirements:
78
+ - - ">="
79
+ - !ruby/object:Gem::Version
80
+ version: '0'
81
+ required_rubygems_version: !ruby/object:Gem::Requirement
82
+ requirements:
83
+ - - ">="
84
+ - !ruby/object:Gem::Version
85
+ version: '0'
86
+ requirements: []
87
+ rubyforge_project:
88
+ rubygems_version: 2.4.5
89
+ signing_key:
90
+ specification_version: 4
91
+ summary: A Rails pagination JSON handler, perfect for API
92
+ test_files: []
93
+ has_rdoc: