http-rest_client 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
+ SHA256:
3
+ metadata.gz: 45f0d996a5e716ad0cbfcda3a5ce5d8325265525a6ac38afa314f76975fed137
4
+ data.tar.gz: 7d9de2eb1e65ccae3e1974c8cb2737515b3c70ac25d993c908f909d91b21f5f1
5
+ SHA512:
6
+ metadata.gz: 67a4612079fd9a607c1a3346921956b7192c4f26e7e805ec24a0c1d83a43eddf43264d7986e81a6c0ce6c8046f1044fc316342d0bb37ce72e4db9eaeafb76a7e
7
+ data.tar.gz: 04e28de3011e9910b6d659d5ccb89a602c47052e53a4ac3802253658b385b7bb8ba7737090fa113673917989ddb65b9d41a7a662757ad14b568d47305deb318d
@@ -0,0 +1,14 @@
1
+ workflow "Tests" {
2
+ on = "push"
3
+ resolves = [
4
+ "Runs tests on Ruby 2.6",
5
+ ]
6
+ }
7
+
8
+ action "Runs tests on Ruby 2.6" {
9
+ uses = "docker://ruby:2.6-alpine"
10
+ args = [
11
+ "sh", "-c",
12
+ "apk add -U git build-base && bundle install && rake"
13
+ ]
14
+ }
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/.rubocop.yml ADDED
@@ -0,0 +1,53 @@
1
+ require:
2
+ - rubocop-performance
3
+ - rubocop-rspec
4
+
5
+ RSpec:
6
+ Enabled: true
7
+
8
+ Performance:
9
+ Enabled: true
10
+
11
+ Bundler:
12
+ Enabled: true
13
+
14
+ Gemspec:
15
+ Enabled: true
16
+
17
+ Style/StringLiterals:
18
+ Enabled: true
19
+ EnforcedStyle: single_quotes
20
+
21
+ Style/FrozenStringLiteralComment:
22
+ Enabled: false
23
+
24
+ Metrics/LineLength:
25
+ Max: 80
26
+
27
+ Metrics/BlockLength:
28
+ Exclude:
29
+ - 'spec/**/*_spec.rb'
30
+ - '**/*.gemspec'
31
+
32
+ Layout/IndentationConsistency:
33
+ EnforcedStyle: normal
34
+
35
+ Style/BlockDelimiters:
36
+ Enabled: true
37
+
38
+ RSpec/FilePath:
39
+ Exclude:
40
+ - 'spec/**/*_spec.rb'
41
+
42
+ RSpec/DescribedClass:
43
+ Exclude:
44
+ - 'spec/integration/*_spec.rb'
45
+
46
+ RSpec/ExampleLength:
47
+ Enabled: false
48
+
49
+ RSpec/MultipleExpectations:
50
+ Enabled: false
51
+
52
+ RSpec/ContextWording:
53
+ Enabled: false
data/.yardstick.yml ADDED
@@ -0,0 +1,30 @@
1
+ ---
2
+ path: ['lib/**/*.rb']
3
+ threshold: 100
4
+ rules:
5
+ ApiTag::Presence:
6
+ enabled: false
7
+ ApiTag::Inclusion:
8
+ enabled: false
9
+ ApiTag::ProtectedMethod:
10
+ enabled: false
11
+ ApiTag::PrivateMethod:
12
+ enabled: false
13
+ ExampleTag:
14
+ enabled: false
15
+ ReturnTag:
16
+ enabled: true
17
+ exclude: []
18
+ Summary::Presence:
19
+ enabled: true
20
+ exclude: []
21
+ Summary::Length:
22
+ enabled: true
23
+ exclude: []
24
+ Summary::Delimiter:
25
+ enabled: true
26
+ exclude: []
27
+ Summary::SingleLine:
28
+ enabled: true
29
+ exclude: []
30
+
@@ -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,
8
+ body size, disability, ethnicity, gender identity and expression, level of
9
+ experience, nationality, personal appearance, race, religion, or sexual
10
+ identity and 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
52
+ appointed representative at an online or offline event. Representation of a
53
+ project may be 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 stas@nerd.ro. All complaints will be
59
+ reviewed and investigated and will result in a response that is deemed
60
+ necessary and appropriate to the circumstances. The project team is obligated
61
+ 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 [http://contributor-covenant.org/version/1/4][version]
72
+
73
+ [homepage]: http://contributor-covenant.org
74
+ [version]: http://contributor-covenant.org/version/1/4/
data/Gemfile ADDED
@@ -0,0 +1,3 @@
1
+ source 'https://rubygems.org'
2
+
3
+ gemspec
data/Gemfile.lock ADDED
@@ -0,0 +1,86 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ http-rest_client (0.1.0)
5
+ http
6
+
7
+ GEM
8
+ remote: https://rubygems.org/
9
+ specs:
10
+ addressable (2.6.0)
11
+ public_suffix (>= 2.0.2, < 4.0)
12
+ ast (2.4.0)
13
+ diff-lcs (1.3)
14
+ docile (1.3.2)
15
+ domain_name (0.5.20180417)
16
+ unf (>= 0.0.5, < 1.0.0)
17
+ http (4.1.1)
18
+ addressable (~> 2.3)
19
+ http-cookie (~> 1.0)
20
+ http-form_data (~> 2.0)
21
+ http_parser.rb (~> 0.6.0)
22
+ http-cookie (1.0.3)
23
+ domain_name (~> 0.5)
24
+ http-form_data (2.1.1)
25
+ http_parser.rb (0.6.0)
26
+ jaro_winkler (1.5.3)
27
+ json (2.2.0)
28
+ parallel (1.17.0)
29
+ parser (2.6.3.0)
30
+ ast (~> 2.4.0)
31
+ public_suffix (3.1.1)
32
+ rainbow (3.0.0)
33
+ rake (12.3.2)
34
+ rspec (3.8.0)
35
+ rspec-core (~> 3.8.0)
36
+ rspec-expectations (~> 3.8.0)
37
+ rspec-mocks (~> 3.8.0)
38
+ rspec-core (3.8.1)
39
+ rspec-support (~> 3.8.0)
40
+ rspec-expectations (3.8.4)
41
+ diff-lcs (>= 1.2.0, < 2.0)
42
+ rspec-support (~> 3.8.0)
43
+ rspec-mocks (3.8.1)
44
+ diff-lcs (>= 1.2.0, < 2.0)
45
+ rspec-support (~> 3.8.0)
46
+ rspec-support (3.8.2)
47
+ rubocop (0.71.0)
48
+ jaro_winkler (~> 1.5.1)
49
+ parallel (~> 1.10)
50
+ parser (>= 2.6)
51
+ rainbow (>= 2.2.2, < 4.0)
52
+ ruby-progressbar (~> 1.7)
53
+ unicode-display_width (>= 1.4.0, < 1.7)
54
+ rubocop-performance (1.3.0)
55
+ rubocop (>= 0.68.0)
56
+ rubocop-rspec (1.33.0)
57
+ rubocop (>= 0.60.0)
58
+ ruby-progressbar (1.10.1)
59
+ simplecov (0.16.1)
60
+ docile (~> 1.1)
61
+ json (>= 1.8, < 3)
62
+ simplecov-html (~> 0.10.0)
63
+ simplecov-html (0.10.2)
64
+ unf (0.1.4)
65
+ unf_ext
66
+ unf_ext (0.0.7.6)
67
+ unicode-display_width (1.6.0)
68
+ yard (0.9.19)
69
+ yardstick (0.9.9)
70
+ yard (~> 0.8, >= 0.8.7.2)
71
+
72
+ PLATFORMS
73
+ ruby
74
+
75
+ DEPENDENCIES
76
+ bundler
77
+ http-rest_client!
78
+ rake
79
+ rspec
80
+ rubocop-performance
81
+ rubocop-rspec
82
+ simplecov
83
+ yardstick
84
+
85
+ BUNDLED WITH
86
+ 1.17.2
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2019 Stas SUȘCOV
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,140 @@
1
+ # HTTP Rest Client
2
+
3
+ A simple HTTP API Client built on top of
4
+ [http.rb](https://github.com/httprb/http). The interface was borrowed from Nestful.
5
+
6
+ ## About
7
+
8
+ The library represents a thin wrapper (~100 lines of code) over the wonderful
9
+ `http.rb` gem, allowing you to define and interact with a RESTful API in an
10
+ Active Record style using plain old Ruby objects.
11
+
12
+ Main goals:
13
+ * No _magic_ please
14
+ * Clean and minimal DSL
15
+ * Less code, less maintenance
16
+ * Good docs and test coverage
17
+ * Keep it up-to-date (or at least tell people this is no longer maintained)
18
+
19
+ This library exists because similar projects are either:
20
+ * no longer maintained
21
+ * implement features which `http.rb` offers and thus have a higher complexity
22
+ * have other very specific features (like relationships, xml or other flavour
23
+ response types support)
24
+
25
+ ## Installation
26
+
27
+ Add this line to your application's Gemfile:
28
+
29
+ ```ruby
30
+ gem 'http-rest_client'
31
+ ```
32
+
33
+ And then execute:
34
+
35
+ ```ruby
36
+ $ bundle
37
+ ```
38
+
39
+ Or install it yourself as:
40
+
41
+ ```ruby
42
+ $ gem install http-rest_client
43
+ ```
44
+
45
+ ## Usage
46
+
47
+ This library provides composable modules/mixins to allow you build flexible
48
+ interfaces/wrappers for RESTful APIs.
49
+
50
+ ### DSL
51
+
52
+ The `HTTP::RestClient::DSL` mixin provides a couple of helpers to define
53
+ the API endpoint, path and content type. It also takes care of the error
54
+ handling and the parsing of the responses.
55
+
56
+ The following class methods are provided by this mixin:
57
+ * `endpoint('http://api.tld')` - sets up the API URI
58
+ * `path('/resource')` - defines the API path of the resource
59
+ * `content_type('application/json')` - sets up the content type of the request
60
+ * `accept('application/json')` - sets up the response media type
61
+ * `basic_auth(user: 'username', pass: 'password')` - sets up the basic
62
+ authentication user and password
63
+ * `auth('AUTH_TOKEN')` - sets up the authentication token
64
+ * `request('get', uri, options)` - creates a request and handles the response
65
+
66
+ ### CRUD
67
+
68
+ The `HTTP::RestClient::CRUD` mixin provides the _create-read-update-delete_ helpers
69
+ to help you define Active Record style classes representing the API resources.
70
+
71
+ The following class methods are provided by this mixin:
72
+ * `all(params)` - returns all available resources
73
+ * `find(id, params)` - returns the available resource based on the `id`
74
+ * `create(params)` - creates and returns the new resource using the passed data
75
+ * `update(id, params)` - updates and returns the resource using the passed data
76
+ * `delete(id)` - removes the resource
77
+
78
+ #### Resource definition
79
+
80
+ Let's take the example below as an API resource we want to work with:
81
+ ```ruby
82
+ require 'ostruct'
83
+
84
+ class MyResource < OpenStruct
85
+ extend HTTP::RestClient::DSL
86
+ extend HTTP::RestClient::CRUD
87
+
88
+ endpoint 'https://httpbin.org'
89
+ path 'anything'
90
+ content_type 'application/json'
91
+ accept 'application/json'
92
+ basic_auth user: 'user1', pass: 'pass1'
93
+ # Alternatively, define the token based authentication
94
+ # auth('MY_API_TOKEN')
95
+ end
96
+ ```
97
+ The class inherits the `OpenStruct` interface which allows an easy way to have
98
+ dynamic class attributes. And for testing purposes, we will use the HTTPBin
99
+ web service to mock any responses.
100
+
101
+ Now we can operate on the new resource endpoint in a pragmatic way:
102
+
103
+ ```ruby
104
+ > res_one = MyResource.create(attr: :attr_value)
105
+ > res_one.json
106
+ => {"attr"=>"attr_value"}
107
+ > res_one['method']
108
+ => "POST"
109
+ ```
110
+
111
+ ## Development
112
+
113
+ After checking out the repo, run `bundle` to install dependencies.
114
+
115
+ Then, run `rake` to run the tests.
116
+
117
+ To install this gem onto your local machine, run `bundle exec rake install`.
118
+
119
+ To release a new version, update the version number in `version.rb`, and then
120
+ run `bundle exec rake release`, which will create a git tag for the version,
121
+ push git commits and tags, and push the `.gem` file to
122
+ [rubygems.org](https://rubygems.org).
123
+
124
+ ## Contributing
125
+
126
+ Bug reports and pull requests are welcome on GitHub at
127
+ https://github.com/stas/http-rest_client. This project is intended to be
128
+ a safe, welcoming space for collaboration, and contributors are expected to
129
+ adhere to the [Contributor Covenant](http://contributor-covenant.org) code of
130
+ conduct.
131
+
132
+ ## License
133
+
134
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
135
+
136
+ ## Code of Conduct
137
+
138
+ Everyone interacting with this project codebase, issue
139
+ tracker, chat rooms and mailing list is expected to follow the [code of
140
+ conduct](https://github.com/[USERNAME]/active_record_pgcrypto/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,23 @@
1
+ require 'bundler/gem_tasks'
2
+ require 'rspec/core/rake_task'
3
+ require 'rubocop/rake_task'
4
+ require 'yaml'
5
+ require 'yardstick/rake/verify'
6
+
7
+ desc('Documentation stats and measurements')
8
+ task('qa:docs') do
9
+ yaml = YAML.load_file('.yardstick.yml')
10
+ config = Yardstick::Config.coerce(yaml)
11
+ measure = Yardstick.measure(config)
12
+ measure.puts
13
+ coverage = Yardstick.round_percentage(measure.coverage * 100)
14
+ exit(1) if coverage < config.threshold
15
+ end
16
+
17
+ RuboCop::RakeTask.new('qa:code')
18
+
19
+ desc('Run QA tasks')
20
+ task(qa: ['qa:docs', 'qa:code'])
21
+
22
+ RSpec::Core::RakeTask.new(spec: :qa)
23
+ task(default: :spec)
@@ -0,0 +1,31 @@
1
+ lib = File.expand_path('lib', __dir__)
2
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
3
+ require 'http/rest_client/version'
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = 'http-rest_client'
7
+ spec.version = HTTP::RestClient::VERSION
8
+ spec.authors = ['Stas SUȘCOV']
9
+ spec.email = ['stas@nerd.ro']
10
+
11
+ spec.summary = 'An easy to use HTTP/REST client'
12
+ spec.description = 'A HTTP/REST Client to help you wrap APIs easily.'
13
+ spec.homepage = 'https://github.com/stas/http-rest_client'
14
+ spec.license = 'MIT'
15
+
16
+ # Specify which files should be added to the gem when it is released.
17
+ spec.files = Dir.chdir(File.expand_path(__dir__)) do
18
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(spec)/}) }
19
+ end
20
+ spec.require_paths = ['lib']
21
+
22
+ spec.add_dependency 'http'
23
+
24
+ spec.add_development_dependency 'bundler'
25
+ spec.add_development_dependency 'rake'
26
+ spec.add_development_dependency 'rspec'
27
+ spec.add_development_dependency 'rubocop-performance'
28
+ spec.add_development_dependency 'rubocop-rspec'
29
+ spec.add_development_dependency 'simplecov'
30
+ spec.add_development_dependency 'yardstick'
31
+ end
@@ -0,0 +1,9 @@
1
+ require 'http/rest_client/dsl'
2
+ require 'http/rest_client/crud'
3
+ require 'http/rest_client/version'
4
+
5
+ module HTTP
6
+ # A simple HTTP API Client built on top of `http.rb`.
7
+ module RestClient
8
+ end
9
+ end
@@ -0,0 +1,64 @@
1
+ module HTTP
2
+ module RestClient
3
+ # Create/Read/Update/Delete helpers.
4
+ module CRUD
5
+ # Resource collection finder, uses the default limit
6
+ #
7
+ # @param params [Hash] URI parameters to pass to the endpoint.
8
+ # @return [Array] of [Object] instances
9
+ def all(params = {})
10
+ objectify(request(:get, uri, params: params))
11
+ end
12
+
13
+ # Resource finder
14
+ #
15
+ # @param id [String] resource indentifier
16
+ # @param params [Hash] URI parameters to pass to the endpoint.
17
+ # @return [Object] instance
18
+ def find(id, params = {})
19
+ objectify(request(:get, uri(id), params: params))
20
+ end
21
+
22
+ # Resource deletion handler
23
+ #
24
+ # @param id [String] resource indentifier
25
+ # @return [Object] instance
26
+ def delete(id)
27
+ objectify(request(:delete, uri(id)))
28
+ end
29
+
30
+ # Resource creation helper
31
+ #
32
+ # @param params [Hash] request parameters to pass to the endpoint as JSON.
33
+ # @return [Object] instance
34
+ def create(params = {})
35
+ objectify(request(:post, uri, json: params))
36
+ end
37
+
38
+ # Resource update helper
39
+ #
40
+ # @param id [String] resource indentifier
41
+ # @param params [Hash] request parameters to pass to the endpoint as JSON.
42
+ # @return [Object] instance
43
+ def update(id, params = {})
44
+ objectify(request(:patch, uri(id), json: params))
45
+ end
46
+
47
+ private
48
+
49
+ # Resource constructor wrapper
50
+ #
51
+ # @param payload [Hash] response payload to build a resource.
52
+ # @return [Object] instance or a list of instances.
53
+ def objectify(payload)
54
+ if payload.is_a?(Array)
55
+ payload.map { |data| new(data) }
56
+ elsif payload.is_a?(Hash)
57
+ new(payload)
58
+ else
59
+ payload
60
+ end
61
+ end
62
+ end
63
+ end
64
+ end
@@ -0,0 +1,147 @@
1
+ require 'base64'
2
+ require 'http'
3
+ require 'http/rest_client/response_error'
4
+
5
+ module HTTP
6
+ module RestClient
7
+ # Client DSL, mostly inpired from Nestful and HTTP::Chainable APIs.
8
+ module DSL
9
+ # Copy/alias over some methods.
10
+ define_method :auth, Chainable.instance_method(:auth)
11
+ define_method :basic_auth, Chainable.instance_method(:basic_auth)
12
+
13
+ # Updates the client headers
14
+ #
15
+ # @param header [Hash] a dictionary to assign as a header.
16
+ # @return [Hash]
17
+ def headers(header = nil)
18
+ if header.is_a?(Hash)
19
+ @headers ||= {}
20
+ @headers.merge!(header)
21
+ end
22
+
23
+ return @headers if @headers
24
+
25
+ superclass.respond_to?(:headers) ? superclass.headers : nil
26
+ end
27
+
28
+ # Defines the client endpoint. Inheritable-safe
29
+ #
30
+ # @param value [String] the endpoint URI.
31
+ # @return [String]
32
+ def endpoint(value = nil)
33
+ @endpoint = value if value
34
+
35
+ return @endpoint if @endpoint
36
+
37
+ superclass.respond_to?(:endpoint) ? superclass.endpoint : nil
38
+ end
39
+
40
+ # Defines the client resource path. Inheritable-safe
41
+ #
42
+ # @param value [String] the endpoint URI path.
43
+ # @return [String]
44
+ def path(value = nil)
45
+ @path = value if value
46
+
47
+ return @path if @path
48
+
49
+ superclass.respond_to?(:path) ? superclass.path : nil
50
+ end
51
+
52
+ # Sets the client expected HTTP request content type
53
+ #
54
+ # @param type [String] the full mime-type name.
55
+ # @return [Hash]
56
+ def content_type(type)
57
+ headers(HTTP::Headers::CONTENT_TYPE => HTTP::MimeType.normalize(type))
58
+ end
59
+
60
+ # Sets the client expected HTTP response media type
61
+ #
62
+ # @param type [String] the full mime-type name.
63
+ # @return [Hash]
64
+ def accept(type)
65
+ headers(HTTP::Headers::ACCEPT => HTTP::MimeType.normalize(type))
66
+ end
67
+
68
+ # Parses and returns the endpoint and path full URL
69
+ #
70
+ # @return [URI]
71
+ def url
72
+ URI.parse(endpoint).join(path.to_s).to_s
73
+ end
74
+
75
+ # Extends the endpoint and path full URL with new parts
76
+ #
77
+ # @param parts [String] a list of parts to extend the base URL.
78
+ # @return [URI]
79
+ def uri(*parts)
80
+ # If an absolute URI already
81
+ return parts.first if parts.first.is_a?(URI) && parts.first.host
82
+
83
+ joined = [url, *parts].map(&:to_s).reject(&:empty?) * '/'
84
+
85
+ URI.parse(joined)
86
+ end
87
+
88
+ # Makes an HTTP request and returns a parsed response where possible
89
+ #
90
+ # @param verb [String] the HTTP method.
91
+ # @param uri [URI] the HTTP URI.
92
+ # @param options [Hash] the params/json-payload/form to include.
93
+ # @return parsed response, can be a [String], a [Hash] or an [Array]
94
+ def request(verb, uri, options = {})
95
+ client = HTTP::Client.new(headers: headers)
96
+ handle_response(client.request(verb, uri, options))
97
+ end
98
+
99
+ # Response handler, raises an [HTTP::RestClient::ResponseError] on errors
100
+ #
101
+ # @param response [HTTP::Response] object
102
+ # @return [Hash] on parsable responses, alternatively the raw response
103
+ def handle_response(response)
104
+ parsed = parse_response(response)
105
+
106
+ return parsed unless error_response?(response, parsed)
107
+
108
+ raise ResponseError.new(extract_error(response, parsed), parsed)
109
+ end
110
+
111
+ # Will try to parse the response
112
+ #
113
+ # Will return nothing on failure.
114
+ #
115
+ # @param response [HTTP::Response] the server response
116
+ #
117
+ # @return [Object] upon success
118
+ def parse_response(response)
119
+ response.parse
120
+ rescue HTTP::Error
121
+ nil
122
+ end
123
+
124
+ # Extracts the error message from the response
125
+ #
126
+ # @param response [HTTP::Response] the server response
127
+ # @param _parsed_response [Object] the parsed server response
128
+ #
129
+ # @return [String]
130
+ def extract_error(response, _parsed_response)
131
+ [response.status.to_s, response.body.to_str].reject(&:empty?).join(': ')
132
+ end
133
+
134
+ # Validate error response
135
+ #
136
+ # Looks at the response code by default.
137
+ #
138
+ # @param response [HTTP::Response] the server response
139
+ # @param _parsed_response [Object] the parsed server response
140
+ #
141
+ # @return [TrueClass] if status code is not a successful standard value
142
+ def error_response?(response, _parsed_response)
143
+ !(200..299).cover?(response.code)
144
+ end
145
+ end
146
+ end
147
+ end
@@ -0,0 +1,22 @@
1
+ module HTTP
2
+ module RestClient
3
+ # Client default response exception class.
4
+ class ResponseError < StandardError
5
+ # Error additional data
6
+ #
7
+ # @return [Hash]
8
+ attr_reader :response_data
9
+
10
+ # Class constructor
11
+ #
12
+ # @param message [String] the error details
13
+ # @param data [Hash] the error data
14
+ #
15
+ # @return [ResponseError] instance
16
+ def initialize(message, data)
17
+ super(message)
18
+ @response_data = data.as_json if data
19
+ end
20
+ end
21
+ end
22
+ end
@@ -0,0 +1,5 @@
1
+ module HTTP
2
+ module RestClient
3
+ VERSION = '0.1.0'.freeze
4
+ end
5
+ end
metadata ADDED
@@ -0,0 +1,171 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: http-rest_client
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Stas SUȘCOV
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2019-06-29 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: http
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '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'
27
+ - !ruby/object:Gem::Dependency
28
+ name: bundler
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: '0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rake
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - ">="
46
+ - !ruby/object:Gem::Version
47
+ version: '0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: '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: '0'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - ">="
67
+ - !ruby/object:Gem::Version
68
+ version: '0'
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: '0'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - ">="
81
+ - !ruby/object:Gem::Version
82
+ version: '0'
83
+ - !ruby/object:Gem::Dependency
84
+ name: rubocop-rspec
85
+ requirement: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - ">="
88
+ - !ruby/object:Gem::Version
89
+ version: '0'
90
+ type: :development
91
+ prerelease: false
92
+ version_requirements: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - ">="
95
+ - !ruby/object:Gem::Version
96
+ version: '0'
97
+ - !ruby/object:Gem::Dependency
98
+ name: simplecov
99
+ requirement: !ruby/object:Gem::Requirement
100
+ requirements:
101
+ - - ">="
102
+ - !ruby/object:Gem::Version
103
+ version: '0'
104
+ type: :development
105
+ prerelease: false
106
+ version_requirements: !ruby/object:Gem::Requirement
107
+ requirements:
108
+ - - ">="
109
+ - !ruby/object:Gem::Version
110
+ version: '0'
111
+ - !ruby/object:Gem::Dependency
112
+ name: yardstick
113
+ requirement: !ruby/object:Gem::Requirement
114
+ requirements:
115
+ - - ">="
116
+ - !ruby/object:Gem::Version
117
+ version: '0'
118
+ type: :development
119
+ prerelease: false
120
+ version_requirements: !ruby/object:Gem::Requirement
121
+ requirements:
122
+ - - ">="
123
+ - !ruby/object:Gem::Version
124
+ version: '0'
125
+ description: A HTTP/REST Client to help you wrap APIs easily.
126
+ email:
127
+ - stas@nerd.ro
128
+ executables: []
129
+ extensions: []
130
+ extra_rdoc_files: []
131
+ files:
132
+ - ".github/main.workflow"
133
+ - ".gitignore"
134
+ - ".rubocop.yml"
135
+ - ".yardstick.yml"
136
+ - CODE_OF_CONDUCT.md
137
+ - Gemfile
138
+ - Gemfile.lock
139
+ - LICENSE.txt
140
+ - README.md
141
+ - Rakefile
142
+ - http-rest_client.gemspec
143
+ - lib/http/rest_client.rb
144
+ - lib/http/rest_client/crud.rb
145
+ - lib/http/rest_client/dsl.rb
146
+ - lib/http/rest_client/response_error.rb
147
+ - lib/http/rest_client/version.rb
148
+ homepage: https://github.com/stas/http-rest_client
149
+ licenses:
150
+ - MIT
151
+ metadata: {}
152
+ post_install_message:
153
+ rdoc_options: []
154
+ require_paths:
155
+ - lib
156
+ required_ruby_version: !ruby/object:Gem::Requirement
157
+ requirements:
158
+ - - ">="
159
+ - !ruby/object:Gem::Version
160
+ version: '0'
161
+ required_rubygems_version: !ruby/object:Gem::Requirement
162
+ requirements:
163
+ - - ">="
164
+ - !ruby/object:Gem::Version
165
+ version: '0'
166
+ requirements: []
167
+ rubygems_version: 3.0.1
168
+ signing_key:
169
+ specification_version: 4
170
+ summary: An easy to use HTTP/REST client
171
+ test_files: []