api_versioner 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 357247c1ecd0b2e666c8bdbbdac1b3eb9a22522308c699bf29ae91c7dd865747
4
+ data.tar.gz: a0f4129bf5aa8268bca4bf5402c1adb5162c18f0b7113475e1cf5058efa6cd04
5
+ SHA512:
6
+ metadata.gz: f5ca13ee2c3708845606d16e762cbc59f75271ddb44966e5290fb8b0d5b514834226a8c8111ccd05509b28a39356aab975907c56f33e0c7e9557ee5a90d9fe1e
7
+ data.tar.gz: e2e7a61081408844376ee544880f60164160956d24a32d934f2918a170e5864a7582d4d28e6581d85f3f52f37c3dc695dd54b5106dee0be64e920f345125fdcf
@@ -0,0 +1,19 @@
1
+ # See here for image contents: https://github.com/microsoft/vscode-dev-containers/tree/v0.194.3/containers/ruby/.devcontainer/base.Dockerfile
2
+
3
+ # [Choice] Ruby version: 3, 3.0, 2, 2.7, 2.6
4
+ ARG VARIANT="3.0"
5
+ FROM mcr.microsoft.com/vscode/devcontainers/ruby:0-${VARIANT}
6
+
7
+ # [Choice] Node.js version: none, lts/*, 16, 14, 12, 10
8
+ ARG NODE_VERSION="none"
9
+ RUN if [ "${NODE_VERSION}" != "none" ]; then su vscode -c "umask 0002 && . /usr/local/share/nvm/nvm.sh && nvm install ${NODE_VERSION} 2>&1"; fi
10
+
11
+ # [Optional] Uncomment this section to install additional OS packages.
12
+ # RUN apt-get update && export DEBIAN_FRONTEND=noninteractive \
13
+ # && apt-get -y install --no-install-recommends <your-package-list-here>
14
+
15
+ # [Optional] Uncomment this line to install additional gems.
16
+ # RUN gem install <your-gem-names-here>
17
+
18
+ # [Optional] Uncomment this line to install global node packages.
19
+ # RUN su vscode -c "source /usr/local/share/nvm/nvm.sh && npm install -g <your-package-here>" 2>&1
@@ -0,0 +1,32 @@
1
+ // For format details, see https://aka.ms/devcontainer.json. For config options, see the README at:
2
+ // https://github.com/microsoft/vscode-dev-containers/tree/v0.194.3/containers/ruby
3
+ {
4
+ "name": "Ruby",
5
+ "build": {
6
+ "dockerfile": "Dockerfile",
7
+ "args": {
8
+ // Update 'VARIANT' to pick a Ruby version: 3, 3.0, 2, 2.7, 2.6
9
+ "VARIANT": "2.7",
10
+ // Options
11
+ "NODE_VERSION": "none"
12
+ }
13
+ },
14
+
15
+ // Set *default* container specific settings.json values on container create.
16
+ "settings": {},
17
+
18
+ // Add the IDs of extensions you want installed when the container is created.
19
+ "extensions": [
20
+ "rebornix.Ruby"
21
+ ],
22
+
23
+ // Use 'forwardPorts' to make a list of ports inside the container available locally.
24
+ // "forwardPorts": [],
25
+
26
+ // Use 'postCreateCommand' to run commands after the container is created.
27
+ // "postCreateCommand": "ruby --version",
28
+
29
+ // Comment out connect as root instead. More info: https://aka.ms/vscode-remote/containers/non-root.
30
+ "remoteUser": "vscode"
31
+
32
+ }
data/.gitignore ADDED
@@ -0,0 +1,11 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+
10
+ # rspec failure tracking
11
+ .rspec_status
data/.reek.yml ADDED
@@ -0,0 +1,17 @@
1
+ ---
2
+ detectors:
3
+ Attribute:
4
+ enabled: false
5
+
6
+ ControlParameter:
7
+ enabled: false
8
+
9
+ IrresponsibleModule:
10
+ enabled: false
11
+
12
+ UtilityFunction:
13
+ enabled: false
14
+
15
+ UncommunicativeVariableName:
16
+ accept:
17
+ - e
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,77 @@
1
+ # https://github.com/bbatsov/rubocop/blob/master/config/default.yml
2
+ require:
3
+ - rubocop-performance
4
+ - rubocop-rspec
5
+
6
+ AllCops:
7
+ NewCops: enable
8
+ CacheRootDirectory: tmp
9
+ Exclude:
10
+ - bin/*
11
+ - vendor/**/*
12
+
13
+ Layout/ArgumentAlignment:
14
+ EnforcedStyle: with_fixed_indentation
15
+
16
+ Metrics/AbcSize:
17
+ Exclude:
18
+ - db/migrate/*
19
+ - config/initializers/auto_inject/*
20
+
21
+ Metrics/BlockLength:
22
+ Exclude:
23
+ - config/environments/*
24
+ - config/initializers/auto_inject/*
25
+ - config/routes.rb
26
+ - config/routes/*
27
+ - db/**/*
28
+ - lib/tasks/**/*
29
+ - spec/**/*
30
+
31
+ Metrics/ClassLength:
32
+ Exclude:
33
+ - db/migrate/*
34
+
35
+ Metrics/MethodLength:
36
+ Exclude:
37
+ - db/migrate/*
38
+ - config/initializers/auto_inject/*
39
+
40
+ RSpec/DescribeClass:
41
+ Exclude:
42
+ - spec/requests/**/*
43
+
44
+ RSpec/EmptyExampleGroup:
45
+ Enabled: false
46
+
47
+ RSpec/ExampleLength:
48
+ Exclude:
49
+ - spec/**/*
50
+
51
+ RSpec/MultipleExpectations:
52
+ Enabled: false
53
+
54
+ RSpec/MultipleMemoizedHelpers:
55
+ Enabled: false
56
+
57
+ RSpec/ScatteredSetup:
58
+ Exclude:
59
+ - spec/integration/**/*
60
+
61
+ RSpec/VariableName:
62
+ IgnoredPatterns:
63
+ - Authorization
64
+
65
+ Style/Documentation:
66
+ Enabled: false
67
+
68
+ Style/LambdaCall:
69
+ EnforcedStyle: braces
70
+
71
+ Style/ClassAndModuleChildren:
72
+ Exclude:
73
+ - lib/**/*
74
+ EnforcedStyle: compact
75
+
76
+ Style/SafeNavigation:
77
+ Enabled: false
data/.travis.yml ADDED
@@ -0,0 +1,6 @@
1
+ ---
2
+ language: ruby
3
+ cache: bundler
4
+ rvm:
5
+ - 2.7.3
6
+ before_install: gem install bundler -v 2.1.4
data/CHANGELOG ADDED
File without changes
@@ -0,0 +1,74 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to making participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, gender identity and expression, level of experience,
9
+ nationality, personal appearance, race, religion, or sexual identity and
10
+ orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ * Using welcoming and inclusive language
18
+ * Being respectful of differing viewpoints and experiences
19
+ * Gracefully accepting constructive criticism
20
+ * Focusing on what is best for the community
21
+ * Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ * The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ * Trolling, insulting/derogatory comments, and personal or political attacks
28
+ * Public or private harassment
29
+ * Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ * Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies both within project spaces and in public spaces
49
+ when an individual is representing the project or its community. Examples of
50
+ representing a project or community include using an official project e-mail
51
+ address, posting via an official social media account, or acting as an appointed
52
+ representative at an online or offline event. Representation of a project may be
53
+ further defined and clarified by project maintainers.
54
+
55
+ ## Enforcement
56
+
57
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
58
+ reported by contacting the project team at agureiev@shakuro.com. All
59
+ complaints will be reviewed and investigated and will result in a response that
60
+ is deemed necessary and appropriate to the circumstances. The project team is
61
+ obligated to maintain confidentiality with regard to the reporter of an incident.
62
+ Further details of specific enforcement policies may be posted separately.
63
+
64
+ Project maintainers who do not follow or enforce the Code of Conduct in good
65
+ faith may face temporary or permanent repercussions as determined by other
66
+ members of the project's leadership.
67
+
68
+ ## Attribution
69
+
70
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71
+ available at [https://contributor-covenant.org/version/1/4][version]
72
+
73
+ [homepage]: https://contributor-covenant.org
74
+ [version]: https://contributor-covenant.org/version/1/4/
data/Gemfile ADDED
@@ -0,0 +1,6 @@
1
+ # frozen_string_literal: true
2
+
3
+ source 'https://rubygems.org'
4
+
5
+ # Specify your gem's dependencies in versioner.gemspec
6
+ gemspec
data/Gemfile.lock ADDED
@@ -0,0 +1,95 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ api_versioner (1.0.0)
5
+ semantic (~> 1.6.1)
6
+
7
+ GEM
8
+ remote: https://rubygems.org/
9
+ specs:
10
+ activesupport (6.1.4.1)
11
+ concurrent-ruby (~> 1.0, >= 1.0.2)
12
+ i18n (>= 1.6, < 2)
13
+ minitest (>= 5.1)
14
+ tzinfo (~> 2.0)
15
+ zeitwerk (~> 2.3)
16
+ ast (2.4.2)
17
+ concurrent-ruby (1.1.9)
18
+ diff-lcs (1.4.4)
19
+ docile (1.4.0)
20
+ i18n (1.8.11)
21
+ concurrent-ruby (~> 1.0)
22
+ kwalify (0.7.2)
23
+ minitest (5.14.4)
24
+ parallel (1.21.0)
25
+ parser (3.0.2.0)
26
+ ast (~> 2.4.1)
27
+ rack (2.2.3)
28
+ rainbow (3.0.0)
29
+ reek (6.0.6)
30
+ kwalify (~> 0.7.0)
31
+ parser (~> 3.0.0)
32
+ rainbow (>= 2.0, < 4.0)
33
+ regexp_parser (2.1.1)
34
+ rexml (3.2.5)
35
+ rspec (3.10.0)
36
+ rspec-core (~> 3.10.0)
37
+ rspec-expectations (~> 3.10.0)
38
+ rspec-mocks (~> 3.10.0)
39
+ rspec-core (3.10.1)
40
+ rspec-support (~> 3.10.0)
41
+ rspec-expectations (3.10.1)
42
+ diff-lcs (>= 1.2.0, < 2.0)
43
+ rspec-support (~> 3.10.0)
44
+ rspec-mocks (3.10.2)
45
+ diff-lcs (>= 1.2.0, < 2.0)
46
+ rspec-support (~> 3.10.0)
47
+ rspec-support (3.10.3)
48
+ rubocop (1.22.3)
49
+ parallel (~> 1.10)
50
+ parser (>= 3.0.0.0)
51
+ rainbow (>= 2.2.2, < 4.0)
52
+ regexp_parser (>= 1.8, < 3.0)
53
+ rexml
54
+ rubocop-ast (>= 1.12.0, < 2.0)
55
+ ruby-progressbar (~> 1.7)
56
+ unicode-display_width (>= 1.4.0, < 3.0)
57
+ rubocop-ast (1.13.0)
58
+ parser (>= 3.0.1.1)
59
+ rubocop-performance (1.12.0)
60
+ rubocop (>= 1.7.0, < 2.0)
61
+ rubocop-ast (>= 0.4.0)
62
+ rubocop-rails (2.12.4)
63
+ activesupport (>= 4.2.0)
64
+ rack (>= 1.1)
65
+ rubocop (>= 1.7.0, < 2.0)
66
+ rubocop-rspec (2.6.0)
67
+ rubocop (~> 1.19)
68
+ ruby-progressbar (1.11.0)
69
+ semantic (1.6.1)
70
+ simplecov (0.21.2)
71
+ docile (~> 1.1)
72
+ simplecov-html (~> 0.11)
73
+ simplecov_json_formatter (~> 0.1)
74
+ simplecov-html (0.12.3)
75
+ simplecov_json_formatter (0.1.3)
76
+ tzinfo (2.0.4)
77
+ concurrent-ruby (~> 1.0)
78
+ unicode-display_width (2.1.0)
79
+ zeitwerk (2.5.1)
80
+
81
+ PLATFORMS
82
+ ruby
83
+
84
+ DEPENDENCIES
85
+ api_versioner!
86
+ reek (~> 6.0)
87
+ rspec (~> 3.10.0)
88
+ rubocop (~> 1.4)
89
+ rubocop-performance (~> 1.5, >= 1.5.2)
90
+ rubocop-rails (~> 2.2)
91
+ rubocop-rspec (~> 2.0)
92
+ simplecov (~> 0.21.2)
93
+
94
+ BUNDLED WITH
95
+ 2.1.4
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2021 Aleksey Gureiev
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,137 @@
1
+ # API Versioner
2
+
3
+ API Versioner is a tiny focused gem that provides support for semantic versioning to API apps. The idea is as follows:
4
+
5
+ - Backend has its current API version that it exposes in the `X-API-Server-Version` response header by default
6
+ - Client requests a certain API version by sending it in the `X-API-Client-Version` request header by default
7
+ - Before processing the request, backend checks the requested version against the current version using some policy and terminates with an error if the version is unsupported.
8
+
9
+ All moving parts (headers names, the policy and the handler) are configurable.
10
+
11
+ ## Middlewares
12
+
13
+ During initialization if the gem sees it's used in a Rails app, it installs two middlewares:
14
+ - `ApiVersioner::ServerVersionMiddleware` places the current version in the response header (defaults to `X-API-Server-Version`). The header name and the current version is configurable.
15
+ - `ApiVersioner::ClientVersionMiddleware` analyzes the version in the said request header (defaults to `X-API-Client-Version`) and checks it against the current server version using a specified policy.
16
+
17
+ ## Installation
18
+
19
+ Add this line to your application's Gemfile:
20
+
21
+ ```ruby
22
+ gem 'api_versioner'
23
+ ```
24
+
25
+ And then execute:
26
+
27
+ $ bundle install
28
+
29
+ Or install it yourself as:
30
+
31
+ $ gem install versioner
32
+
33
+ ## Usage
34
+
35
+ ```ruby
36
+ # config/initializers/versioner.rb
37
+
38
+ Versioner.configure do |config|
39
+ # Current version of the application
40
+ config.current_version = '1.2.3'
41
+
42
+ # The name of the header to set the current server API version
43
+ # Default: 'X-API-Server-Version'
44
+ config.server_version_header = 'X-API-Server-Version'
45
+
46
+ # The header to look for the API version required by the client
47
+ # Default: 'X-API-Client-Version'
48
+ config.client_version_header = 'X-API-Client-Version'
49
+
50
+ # A callable object to check version policy. It's called with current server version
51
+ # and the requested version from the request header (`client_version_header`).
52
+ # If the requested version is unsupported, the `ApiVersioner::UnsupportedVersion` error should be raised.
53
+ config.version_policy = ApiVersioner::DefaultPolicy.new
54
+
55
+ # A callable object to handle the `ApiVersioner::UnsupportedVersion` error in a way
56
+ # specific to your application. It's called with the error and the configuration.
57
+ # The default implementation renders JSON like below and returns it with error code 400.
58
+ config.unsupported_version_handler = ApiVersioner::DefaultHandler.new
59
+ end
60
+ ```
61
+
62
+ ## Policy
63
+
64
+ A policy is a callable object with two arguments, like below:
65
+
66
+ ```ruby
67
+ class CustomPolicy
68
+ def call(current_version, requested_version)
69
+ raise ApiVersioner::UnsupportedVersion, "This version is ..." if some_condition?
70
+ end
71
+ end
72
+ ```
73
+
74
+ A policy should raise the `ApiVersioner::UnsupportedVersion` error if the requested version is unsupported.
75
+
76
+ The default implementation (`ApiVersioner::DefaultPolicy`) passes for:
77
+ - unspecified versions
78
+ - equal versions
79
+ - requested versions that are lower than current on minor and/or patch levels
80
+
81
+ Raises errors for:
82
+ - requested versions that are **lower than current on major level**
83
+ - requested versions that are higher than current
84
+
85
+ ## UnsupportedVersion error
86
+
87
+ `ApiVersioner::UnsupportedVersion` error has `reason` field that is not initialized by default. You can initialize it with your own value as necessary. This value is returned in the error meta-section by the `ApiVersioner::DefaultHandler` as shown in the next section.
88
+
89
+ ## Handler
90
+
91
+ The handler is a callable object that generates the response when an unsupported version is detected.
92
+
93
+ ```ruby
94
+ class CustomHandler
95
+ def call(error, config)
96
+ [200, {}, ['Version error']]
97
+ end
98
+ end
99
+ ```
100
+
101
+ The default implementation (`ApiVersioner::DefaultHandler`):
102
+ - Returns status 400 (Bad Request)
103
+ - Renders JSON content as follows:
104
+
105
+ ```json
106
+ {
107
+ "errors": [
108
+ {
109
+ "title": "Error message ...",
110
+ "status": 400,
111
+ "code": "UNSUPPORTED_VERSION",
112
+ "meta": {
113
+ "reason": <error.reason>
114
+ }
115
+ }
116
+ ]
117
+ }
118
+ ```
119
+
120
+ Default policy reason codes are:
121
+ - `TOO_LOW` - major number of the requested version is lower than current
122
+ - `TOO_HIGH` - requested version is higher than current on any level
123
+
124
+ ## Development
125
+
126
+ 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.
127
+
128
+ 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).
129
+
130
+ ## Contributing
131
+
132
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/versioner. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/[USERNAME]/versioner/blob/master/CODE_OF_CONDUCT.md).
133
+
134
+
135
+ ## License
136
+
137
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
data/Rakefile ADDED
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'bundler/gem_tasks'
4
+ require 'rspec/core/rake_task'
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ task default: :spec
@@ -0,0 +1,38 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'lib/api_versioner/version'
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = 'api_versioner'
7
+ spec.version = ApiVersioner::VERSION
8
+ spec.authors = ['Aleksey Gureiev']
9
+ spec.email = %w[agureiev@shakuro.com]
10
+
11
+ spec.summary = 'A simple gem to add semantic versioning support to API applications.'
12
+ spec.homepage = 'https://github.com/alg/api_versioner'
13
+ spec.license = 'MIT'
14
+ spec.required_ruby_version = Gem::Requirement.new('>= 2.5.0')
15
+
16
+ spec.metadata['homepage_uri'] = spec.homepage
17
+ spec.metadata['source_code_uri'] = 'https://github.com/alg/api_versioner'
18
+ spec.metadata['changelog_uri'] = 'https://github.com/alg/api_versioner/CHANGELOG'
19
+
20
+ # Specify which files should be added to the gem when it is released.
21
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
22
+ spec.files = Dir.chdir(File.expand_path(__dir__)) do
23
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
24
+ end
25
+ spec.bindir = 'exe'
26
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
27
+ spec.require_paths = %w[lib]
28
+
29
+ spec.add_dependency 'semantic', '~> 1.6.1'
30
+
31
+ spec.add_development_dependency 'reek', '~> 6.0'
32
+ spec.add_development_dependency 'rspec', '~> 3.10.0'
33
+ spec.add_development_dependency 'rubocop', '~> 1.4'
34
+ spec.add_development_dependency 'rubocop-performance', '~> 1.5', '>= 1.5.2'
35
+ spec.add_development_dependency 'rubocop-rails', '~> 2.2'
36
+ spec.add_development_dependency 'rubocop-rspec', '~> 2.0'
37
+ spec.add_development_dependency 'simplecov', '~> 0.21.2'
38
+ end
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "versioner"
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(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
@@ -0,0 +1,46 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'semantic'
4
+ require 'api_versioner/unsupported_version'
5
+
6
+ module ApiVersioner
7
+ class ClientVersionMiddleware
8
+ def initialize(app, config = nil)
9
+ @app = app
10
+ @config = config || Versioner.config
11
+ end
12
+
13
+ def call(env)
14
+ check_version(env)
15
+ @app.(env)
16
+ rescue ApiVersioner::UnsupportedVersion => e
17
+ @config.unsupported_version_handler.(e, @config)
18
+ end
19
+
20
+ def check_version(env)
21
+ return unless checking_versions?
22
+
23
+ @config.version_policy.(@config.current_version, client_version(env))
24
+ end
25
+
26
+ def checking_versions?
27
+ @config.client_version_header &&
28
+ @config.current_version &&
29
+ @config.version_policy &&
30
+ @config.unsupported_version_handler
31
+ end
32
+
33
+ def client_version(env)
34
+ header_name = convert_to_rack_header(@config.client_version_header)
35
+ ver = env[header_name]
36
+
37
+ ver && Semantic::Version.new(ver)
38
+ rescue ArgumentError
39
+ nil
40
+ end
41
+
42
+ def convert_to_rack_header(header)
43
+ "HTTP_#{header.strip.tr('-', '_').upcase}"
44
+ end
45
+ end
46
+ end
@@ -0,0 +1,41 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'semantic'
4
+ require_relative 'default_policy'
5
+ require_relative 'default_handler'
6
+
7
+ module ApiVersioner
8
+ # :reek:TooManyInstanceVariables
9
+ class Configuration
10
+ DEFAULT_SERVER_VERSION_HEADER = 'X-API-Server-Version'
11
+ DEFAULT_CLIENT_VERSION_HEADER = 'X-API-Client-Version'
12
+ DEFAULT_VERSION_POLICY = DefaultPolicy.new
13
+ DEFAULT_UNSUPPORTED_VERSION_HANDLER = DefaultHandler.new
14
+
15
+ attr_accessor :version_policy, :unsupported_version_handler
16
+ attr_reader :current_version, :server_version_header, :client_version_header
17
+
18
+ def initialize
19
+ @current_version = nil
20
+ @server_version_header = DEFAULT_SERVER_VERSION_HEADER
21
+ @client_version_header = DEFAULT_CLIENT_VERSION_HEADER
22
+ @version_policy = DEFAULT_VERSION_POLICY
23
+ @unsupported_version_handler = DEFAULT_UNSUPPORTED_VERSION_HANDLER
24
+ end
25
+
26
+ def current_version=(version)
27
+ ver = version.to_s.strip
28
+ @current_version = ver.empty? ? nil : Semantic::Version.new(ver)
29
+ end
30
+
31
+ def server_version_header=(name)
32
+ val = name.to_s.strip
33
+ @server_version_header = val.empty? ? nil : val
34
+ end
35
+
36
+ def client_version_header=(name)
37
+ val = name.to_s.strip
38
+ @client_version_header = val.empty? ? nil : val
39
+ end
40
+ end
41
+ end
@@ -0,0 +1,28 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'json'
4
+
5
+ module ApiVersioner
6
+ class DefaultHandler
7
+ BLANK_RE = /\A[[:space:]]*\z/.freeze
8
+
9
+ def call(error, _config)
10
+ [400, {}, [JSON.generate(errors: [formatted_error(error)])]]
11
+ end
12
+
13
+ private
14
+
15
+ def formatted_error(error)
16
+ {
17
+ title: error.message,
18
+ status: 400,
19
+ code: 'UNSUPPORTED_VERSION'
20
+ }.tap do |json|
21
+ reason = error.reason
22
+ next if !reason || BLANK_RE.match?(reason)
23
+
24
+ json[:meta] = { reason: reason }
25
+ end
26
+ end
27
+ end
28
+ end
@@ -0,0 +1,44 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'api_versioner/unsupported_version'
4
+
5
+ module ApiVersioner
6
+ class DefaultPolicy
7
+ class VersionTooLow < UnsupportedVersion
8
+ def initialize(msg)
9
+ super(msg, reason: 'TOO_LOW')
10
+ end
11
+ end
12
+
13
+ class VersionTooHigh < UnsupportedVersion
14
+ def initialize(msg)
15
+ super(msg, reason: 'TOO_HIGH')
16
+ end
17
+ end
18
+
19
+ def call(current_version, requested_version)
20
+ return on_version_unspecified unless requested_version
21
+
22
+ on_lower(current_version, requested_version) if requested_version.major < current_version.major
23
+ on_higher(current_version, requested_version) if requested_version > current_version
24
+
25
+ true
26
+ end
27
+
28
+ private
29
+
30
+ def on_version_unspecified
31
+ # Ignore
32
+ end
33
+
34
+ def on_lower(current_version, requested_version)
35
+ raise VersionTooLow,
36
+ "Requested version (#{requested_version}) is significantly lower than current version (#{current_version})"
37
+ end
38
+
39
+ def on_higher(current_version, requested_version)
40
+ raise VersionTooHigh,
41
+ "Requested version (#{requested_version}) is higher than current version (#{current_version})"
42
+ end
43
+ end
44
+ end
@@ -0,0 +1,14 @@
1
+ # frozen_string_literal: true
2
+
3
+ # :nocov:
4
+ require_relative './client_version_middleware'
5
+ require_relative './server_version_middleware'
6
+
7
+ module ApiVersioner
8
+ class Railtie < Rails::Railtie
9
+ initializer 'versioner.configure_rails_initialization' do |app|
10
+ app.middleware.use ServerVersionMiddleware
11
+ app.middleware.insert_after ServerVersionMiddleware, ClientVersionMiddleware
12
+ end
13
+ end
14
+ end
@@ -0,0 +1,31 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ApiVersioner
4
+ class ServerVersionMiddleware
5
+ def initialize(app, config = nil)
6
+ @app = app
7
+ @config = config || ApiVersioner.config
8
+ end
9
+
10
+ def call(env)
11
+ status, headers, response = @app.(env)
12
+
13
+ add_version_header(headers)
14
+
15
+ [status, headers, response]
16
+ end
17
+
18
+ private
19
+
20
+ def add_version_header(headers)
21
+ return unless adding_versions?
22
+
23
+ headers[@config.server_version_header] = @config.current_version.to_s
24
+ end
25
+
26
+ def adding_versions?
27
+ @config.current_version &&
28
+ @config.server_version_header
29
+ end
30
+ end
31
+ end
@@ -0,0 +1,13 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ApiVersioner
4
+ class UnsupportedVersion < StandardError
5
+ attr_reader :reason
6
+
7
+ def initialize(msg = nil, reason: nil)
8
+ super(msg)
9
+
10
+ @reason = reason
11
+ end
12
+ end
13
+ end
@@ -0,0 +1,6 @@
1
+ # frozen_string_literal: true
2
+
3
+ # :nocov:
4
+ module ApiVersioner
5
+ VERSION = '1.0.0'
6
+ end
@@ -0,0 +1,20 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'api_versioner/version'
4
+
5
+ module ApiVersioner
6
+ autoload :Configuration, 'api_versioner/configuration'
7
+
8
+ class << self
9
+ def configure
10
+ yield(config)
11
+ end
12
+
13
+ def config
14
+ @config ||= Configuration.new
15
+ end
16
+ end
17
+ end
18
+
19
+ # :nocov:
20
+ require 'api_versioner/railtie' if defined?(Rails::Railtie)
metadata ADDED
@@ -0,0 +1,190 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: api_versioner
3
+ version: !ruby/object:Gem::Version
4
+ version: 1.0.0
5
+ platform: ruby
6
+ authors:
7
+ - Aleksey Gureiev
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2022-12-14 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: semantic
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: 1.6.1
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: 1.6.1
27
+ - !ruby/object:Gem::Dependency
28
+ name: reek
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '6.0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '6.0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rspec
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: 3.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: 3.10.0
55
+ - !ruby/object:Gem::Dependency
56
+ name: rubocop
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: '1.4'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: '1.4'
69
+ - !ruby/object:Gem::Dependency
70
+ name: rubocop-performance
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - "~>"
74
+ - !ruby/object:Gem::Version
75
+ version: '1.5'
76
+ - - ">="
77
+ - !ruby/object:Gem::Version
78
+ version: 1.5.2
79
+ type: :development
80
+ prerelease: false
81
+ version_requirements: !ruby/object:Gem::Requirement
82
+ requirements:
83
+ - - "~>"
84
+ - !ruby/object:Gem::Version
85
+ version: '1.5'
86
+ - - ">="
87
+ - !ruby/object:Gem::Version
88
+ version: 1.5.2
89
+ - !ruby/object:Gem::Dependency
90
+ name: rubocop-rails
91
+ requirement: !ruby/object:Gem::Requirement
92
+ requirements:
93
+ - - "~>"
94
+ - !ruby/object:Gem::Version
95
+ version: '2.2'
96
+ type: :development
97
+ prerelease: false
98
+ version_requirements: !ruby/object:Gem::Requirement
99
+ requirements:
100
+ - - "~>"
101
+ - !ruby/object:Gem::Version
102
+ version: '2.2'
103
+ - !ruby/object:Gem::Dependency
104
+ name: rubocop-rspec
105
+ requirement: !ruby/object:Gem::Requirement
106
+ requirements:
107
+ - - "~>"
108
+ - !ruby/object:Gem::Version
109
+ version: '2.0'
110
+ type: :development
111
+ prerelease: false
112
+ version_requirements: !ruby/object:Gem::Requirement
113
+ requirements:
114
+ - - "~>"
115
+ - !ruby/object:Gem::Version
116
+ version: '2.0'
117
+ - !ruby/object:Gem::Dependency
118
+ name: simplecov
119
+ requirement: !ruby/object:Gem::Requirement
120
+ requirements:
121
+ - - "~>"
122
+ - !ruby/object:Gem::Version
123
+ version: 0.21.2
124
+ type: :development
125
+ prerelease: false
126
+ version_requirements: !ruby/object:Gem::Requirement
127
+ requirements:
128
+ - - "~>"
129
+ - !ruby/object:Gem::Version
130
+ version: 0.21.2
131
+ description:
132
+ email:
133
+ - agureiev@shakuro.com
134
+ executables: []
135
+ extensions: []
136
+ extra_rdoc_files: []
137
+ files:
138
+ - ".devcontainer/Dockerfile"
139
+ - ".devcontainer/devcontainer.json"
140
+ - ".gitignore"
141
+ - ".reek.yml"
142
+ - ".rspec"
143
+ - ".rubocop.yml"
144
+ - ".travis.yml"
145
+ - CHANGELOG
146
+ - CODE_OF_CONDUCT.md
147
+ - Gemfile
148
+ - Gemfile.lock
149
+ - LICENSE.txt
150
+ - README.md
151
+ - Rakefile
152
+ - api_versioner.gemspec
153
+ - bin/console
154
+ - bin/setup
155
+ - lib/api_versioner.rb
156
+ - lib/api_versioner/client_version_middleware.rb
157
+ - lib/api_versioner/configuration.rb
158
+ - lib/api_versioner/default_handler.rb
159
+ - lib/api_versioner/default_policy.rb
160
+ - lib/api_versioner/railtie.rb
161
+ - lib/api_versioner/server_version_middleware.rb
162
+ - lib/api_versioner/unsupported_version.rb
163
+ - lib/api_versioner/version.rb
164
+ homepage: https://github.com/alg/api_versioner
165
+ licenses:
166
+ - MIT
167
+ metadata:
168
+ homepage_uri: https://github.com/alg/api_versioner
169
+ source_code_uri: https://github.com/alg/api_versioner
170
+ changelog_uri: https://github.com/alg/api_versioner/CHANGELOG
171
+ post_install_message:
172
+ rdoc_options: []
173
+ require_paths:
174
+ - lib
175
+ required_ruby_version: !ruby/object:Gem::Requirement
176
+ requirements:
177
+ - - ">="
178
+ - !ruby/object:Gem::Version
179
+ version: 2.5.0
180
+ required_rubygems_version: !ruby/object:Gem::Requirement
181
+ requirements:
182
+ - - ">="
183
+ - !ruby/object:Gem::Version
184
+ version: '0'
185
+ requirements: []
186
+ rubygems_version: 3.1.6
187
+ signing_key:
188
+ specification_version: 4
189
+ summary: A simple gem to add semantic versioning support to API applications.
190
+ test_files: []