simple_request 0.1.1

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.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: d43c9c4936e8b17e5e8b3b6953f3f1cc2023047af6326ca1ad72087fe74db6ff
4
+ data.tar.gz: c6c4391c995fa95c93d82b3cbc9c93f2d19782d59606959ad84d4b99f8cccf27
5
+ SHA512:
6
+ metadata.gz: 6a1839bd78dfeabd6d9fe0461d2d994afcf959c57b37742438bdfaeb9cd9888966041f29b0d25dd09be6146b5d4a43891650da09a15afa6fb2bce88c0d1cb050
7
+ data.tar.gz: 5f4b1250a0226f84f555f093a9ac6de80d650f2d450718807431800f668bfbced1c4a0e6f7e8041927942a31c66d85c9eed06b812fe5eeb4c85c37e8e65b20fc
@@ -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/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
@@ -0,0 +1,41 @@
1
+ inherit_from: .rubocop_todo.yml
2
+
3
+ require: rubocop-performance
4
+
5
+ # AllCops:
6
+ # TargetRubyVersion: 2.6.2
7
+ # Exclude:
8
+ # - bin/**
9
+ # - db/**/*
10
+ # - node_modules/**/*
11
+
12
+ Documentation:
13
+ Enabled: false
14
+
15
+ Style/Documentation:
16
+ Enabled: false
17
+
18
+ Style/ClassAndModuleChildren:
19
+ Enabled: false
20
+
21
+ Lint/Void:
22
+ Enabled: false
23
+
24
+ Metrics/AbcSize:
25
+ Max: 30
26
+
27
+ Metrics/LineLength:
28
+ Max: 120
29
+
30
+ Metrics/ClassLength:
31
+ Max: 1500
32
+
33
+ Metrics/MethodLength:
34
+ Max: 25
35
+
36
+ Metrics/BlockLength:
37
+ Max: 70
38
+
39
+ Layout/HashAlignment:
40
+ EnforcedHashRocketStyle: table
41
+ EnforcedColonStyle: table
@@ -0,0 +1,278 @@
1
+ # This configuration was generated by
2
+ # `rubocop --auto-gen-config`
3
+ # on 2020-01-01 11:25:12 +0300 using RuboCop version 0.78.0.
4
+ # The point is for the user to remove these configuration records
5
+ # one by one as the offenses are removed from the code base.
6
+ # Note that changes in the inspected code, or installation of new
7
+ # versions of RuboCop, may require this file to be generated again.
8
+
9
+ # Offense count: 1
10
+ # Cop supports --auto-correct.
11
+ # Configuration parameters: EnforcedStyle, IndentationWidth.
12
+ # SupportedStyles: outdent, indent
13
+ Layout/AccessModifierIndentation:
14
+ Exclude:
15
+ - 'lib/simple_helper/response_parser.rb'
16
+
17
+ # Offense count: 3
18
+ # Cop supports --auto-correct.
19
+ # Configuration parameters: EnforcedStyle, IndentOneStep, IndentationWidth.
20
+ # SupportedStyles: case, end
21
+ Layout/CaseIndentation:
22
+ Exclude:
23
+ - 'lib/simple_helper/utils.rb'
24
+
25
+ # Offense count: 3
26
+ # Cop supports --auto-correct.
27
+ Layout/CommentIndentation:
28
+ Exclude:
29
+ - 'Gemfile'
30
+ - 'lib/simple_request.rb'
31
+
32
+ # Offense count: 1
33
+ # Cop supports --auto-correct.
34
+ # Configuration parameters: EnforcedStyleAlignWith, AutoCorrect, Severity.
35
+ # SupportedStylesAlignWith: start_of_line, def
36
+ Layout/DefEndAlignment:
37
+ Exclude:
38
+ - 'lib/simple_helper/response_parser.rb'
39
+
40
+ # Offense count: 1
41
+ # Cop supports --auto-correct.
42
+ # Configuration parameters: AllowAdjacentOneLineDefs, NumberOfEmptyLines.
43
+ Layout/EmptyLineBetweenDefs:
44
+ Exclude:
45
+ - 'lib/simple_helper/const.rb'
46
+
47
+ # Offense count: 1
48
+ # Cop supports --auto-correct.
49
+ Layout/EmptyLines:
50
+ Exclude:
51
+ - 'Gemfile'
52
+
53
+ # Offense count: 1
54
+ # Cop supports --auto-correct.
55
+ # Configuration parameters: EnforcedStyle.
56
+ # SupportedStyles: empty_lines, empty_lines_except_namespace, empty_lines_special, no_empty_lines
57
+ Layout/EmptyLinesAroundModuleBody:
58
+ Exclude:
59
+ - 'lib/simple_helper/utils.rb'
60
+
61
+ # Offense count: 5
62
+ # Cop supports --auto-correct.
63
+ # Configuration parameters: EnforcedStyleAlignWith, AutoCorrect, Severity.
64
+ # SupportedStylesAlignWith: keyword, variable, start_of_line
65
+ Layout/EndAlignment:
66
+ Exclude:
67
+ - 'lib/simple_helper/response_parser.rb'
68
+ - 'lib/simple_helper/utils.rb'
69
+
70
+ # Offense count: 2
71
+ # Cop supports --auto-correct.
72
+ # Configuration parameters: AllowForAlignment, AllowBeforeTrailingComments, ForceEqualSignAlignment.
73
+ Layout/ExtraSpacing:
74
+ Exclude:
75
+ - 'Gemfile'
76
+ - 'simple_request.gemspec'
77
+
78
+ # Offense count: 1
79
+ # Cop supports --auto-correct.
80
+ # Configuration parameters: AllowForAlignment, EnforcedStyleForExponentOperator.
81
+ # SupportedStylesForExponentOperator: space, no_space
82
+ Layout/SpaceAroundOperators:
83
+ Exclude:
84
+ - 'simple_request.gemspec'
85
+
86
+ # Offense count: 2
87
+ # Cop supports --auto-correct.
88
+ # Configuration parameters: EnforcedStyle, EnforcedStyleForEmptyBraces.
89
+ # SupportedStyles: space, no_space
90
+ # SupportedStylesForEmptyBraces: space, no_space
91
+ Layout/SpaceBeforeBlockBraces:
92
+ Exclude:
93
+ - 'lib/simple_helper/utils.rb'
94
+
95
+ # Offense count: 2
96
+ # Cop supports --auto-correct.
97
+ # Configuration parameters: EnforcedStyle, EnforcedStyleForEmptyBraces, SpaceBeforeBlockParameters.
98
+ # SupportedStyles: space, no_space
99
+ # SupportedStylesForEmptyBraces: space, no_space
100
+ Layout/SpaceInsideBlockBraces:
101
+ Exclude:
102
+ - 'lib/simple_helper/utils.rb'
103
+
104
+ # Offense count: 2
105
+ # Cop supports --auto-correct.
106
+ # Configuration parameters: EnforcedStyle.
107
+ # SupportedStyles: final_newline, final_blank_line
108
+ Layout/TrailingEmptyLines:
109
+ Exclude:
110
+ - 'Gemfile'
111
+ - 'lib/simple_helper/constant_data.rb'
112
+
113
+ # Offense count: 1
114
+ # Cop supports --auto-correct.
115
+ # Configuration parameters: AllowInHeredoc.
116
+ Layout/TrailingWhitespace:
117
+ Exclude:
118
+ - 'Gemfile'
119
+
120
+ # Offense count: 2
121
+ Metrics/AbcSize:
122
+ Max: 20
123
+
124
+ # Offense count: 1
125
+ Metrics/CyclomaticComplexity:
126
+ Max: 8
127
+
128
+ # Offense count: 1
129
+ # Configuration parameters: CountComments, ExcludedMethods.
130
+ Metrics/MethodLength:
131
+ Max: 31
132
+
133
+ # Offense count: 1
134
+ Metrics/PerceivedComplexity:
135
+ Max: 9
136
+
137
+ # Offense count: 2
138
+ Naming/ConstantName:
139
+ Exclude:
140
+ - 'lib/simple_helper/constant_data.rb'
141
+
142
+ # Offense count: 1
143
+ # Configuration parameters: NamePrefix, ForbiddenPrefixes, AllowedMethods, MethodDefinitionMacros.
144
+ # NamePrefix: is_, has_, have_
145
+ # ForbiddenPrefixes: is_, has_, have_
146
+ # AllowedMethods: is_a?
147
+ # MethodDefinitionMacros: define_method, define_singleton_method
148
+ Naming/PredicateName:
149
+ Exclude:
150
+ - 'spec/**/*'
151
+ - 'lib/simple_request.rb'
152
+
153
+ # Offense count: 2
154
+ # Cop supports --auto-correct.
155
+ # Configuration parameters: EnforcedStyle, ProceduralMethods, FunctionalMethods, IgnoredMethods, AllowBracesOnProceduralOneLiners.
156
+ # SupportedStyles: line_count_based, semantic, braces_for_chaining, always_braces
157
+ # ProceduralMethods: benchmark, bm, bmbm, create, each_with_object, measure, new, realtime, tap, with_object
158
+ # FunctionalMethods: let, let!, subject, watch
159
+ # IgnoredMethods: lambda, proc, it
160
+ Style/BlockDelimiters:
161
+ Exclude:
162
+ - 'lib/simple_helper/utils.rb'
163
+
164
+ # Offense count: 1
165
+ # Cop supports --auto-correct.
166
+ # Configuration parameters: AutoCorrect, EnforcedStyle.
167
+ # SupportedStyles: nested, compact
168
+ Style/ClassAndModuleChildren:
169
+ Exclude:
170
+ - 'lib/simple_helper/_https.rb'
171
+
172
+ # Offense count: 4
173
+ Style/Documentation:
174
+ Exclude:
175
+ - 'spec/**/*'
176
+ - 'test/**/*'
177
+ - 'lib/simple_helper/const.rb'
178
+ - 'lib/simple_helper/response_parser.rb'
179
+ - 'lib/simple_helper/utils.rb'
180
+ - 'lib/simple_request.rb'
181
+
182
+ # Offense count: 2
183
+ # Cop supports --auto-correct.
184
+ Style/EachWithObject:
185
+ Exclude:
186
+ - 'lib/simple_helper/utils.rb'
187
+
188
+ # Offense count: 1
189
+ # Cop supports --auto-correct.
190
+ Style/ExpandPathArguments:
191
+ Exclude:
192
+ - 'simple_request.gemspec'
193
+
194
+ # Offense count: 8
195
+ # Cop supports --auto-correct.
196
+ # Configuration parameters: EnforcedStyle.
197
+ # SupportedStyles: always, never
198
+ Style/FrozenStringLiteralComment:
199
+ Exclude:
200
+ - 'Gemfile'
201
+ - 'Rakefile'
202
+ - 'bin/console'
203
+ - 'lib/simple_helper/exceptions.rb'
204
+ - 'lib/simple_helper/version.rb'
205
+ - 'simple_request.gemspec'
206
+ - 'spec/simple_request_spec.rb'
207
+ - 'spec/spec_helper.rb'
208
+
209
+ # Offense count: 1
210
+ # Configuration parameters: MinBodyLength.
211
+ Style/GuardClause:
212
+ Exclude:
213
+ - 'lib/simple_request.rb'
214
+
215
+ # Offense count: 1
216
+ # Cop supports --auto-correct.
217
+ # Configuration parameters: EnforcedStyle, UseHashRocketsWithSymbolValues, PreferHashRocketsForNonAlnumEndingSymbols.
218
+ # SupportedStyles: ruby19, hash_rockets, no_mixed_keys, ruby19_no_mixed_keys
219
+ Style/HashSyntax:
220
+ Exclude:
221
+ - 'Rakefile'
222
+
223
+ # Offense count: 1
224
+ # Cop supports --auto-correct.
225
+ Style/IfUnlessModifier:
226
+ Exclude:
227
+ - 'lib/simple_request.rb'
228
+
229
+ # Offense count: 2
230
+ # Cop supports --auto-correct.
231
+ # Configuration parameters: EnforcedStyle.
232
+ # SupportedStyles: literals, strict
233
+ Style/MutableConstant:
234
+ Exclude:
235
+ - 'lib/simple_helper/constant_data.rb'
236
+ - 'lib/simple_helper/version.rb'
237
+
238
+ # Offense count: 1
239
+ # Cop supports --auto-correct.
240
+ # Configuration parameters: PreferredDelimiters.
241
+ Style/PercentLiteralDelimiters:
242
+ Exclude:
243
+ - 'simple_request.gemspec'
244
+
245
+ # Offense count: 1
246
+ # Cop supports --auto-correct.
247
+ Style/RedundantPercentQ:
248
+ Exclude:
249
+ - 'simple_request.gemspec'
250
+
251
+ # Offense count: 32
252
+ # Cop supports --auto-correct.
253
+ # Configuration parameters: EnforcedStyle, ConsistentQuotesInMultiline.
254
+ # SupportedStyles: single_quotes, double_quotes
255
+ Style/StringLiterals:
256
+ Exclude:
257
+ - 'Gemfile'
258
+ - 'Rakefile'
259
+ - 'bin/console'
260
+ - 'lib/simple_helper/version.rb'
261
+ - 'simple_request.gemspec'
262
+ - 'spec/simple_request_spec.rb'
263
+ - 'spec/spec_helper.rb'
264
+
265
+ # Offense count: 1
266
+ # Cop supports --auto-correct.
267
+ # Configuration parameters: WordRegex.
268
+ # SupportedStyles: percent, brackets
269
+ Style/WordArray:
270
+ EnforcedStyle: percent
271
+ MinSize: 3
272
+
273
+ # Offense count: 18
274
+ # Cop supports --auto-correct.
275
+ # Configuration parameters: AutoCorrect, AllowHeredoc, AllowURI, URISchemes, IgnoreCopDirectives, IgnoredPatterns.
276
+ # URISchemes: http, https
277
+ Layout/LineLength:
278
+ Max: 137
@@ -0,0 +1,7 @@
1
+ ---
2
+ sudo: false
3
+ language: ruby
4
+ cache: bundler
5
+ rvm:
6
+ - 2.6.2
7
+ before_install: gem install bundler -v 2.0.2
@@ -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 majed.abdullah@clickapps.co. 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 [http://contributor-covenant.org/version/1/4][version]
72
+
73
+ [homepage]: http://contributor-covenant.org
74
+ [version]: http://contributor-covenant.org/version/1/4/
File without changes
data/Gemfile ADDED
@@ -0,0 +1,8 @@
1
+ source "https://rubygems.org"
2
+
3
+ # Specify your gem's dependencies in simple_request.gemspec
4
+ gemspec
5
+
6
+ group :development, :test do
7
+ gem 'pry'
8
+ end
@@ -0,0 +1,41 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ simple_request (0.1.0)
5
+
6
+ GEM
7
+ remote: https://rubygems.org/
8
+ specs:
9
+ coderay (1.1.2)
10
+ diff-lcs (1.3)
11
+ method_source (0.9.2)
12
+ pry (0.12.2)
13
+ coderay (~> 1.1.0)
14
+ method_source (~> 0.9.0)
15
+ rake (10.5.0)
16
+ rspec (3.9.0)
17
+ rspec-core (~> 3.9.0)
18
+ rspec-expectations (~> 3.9.0)
19
+ rspec-mocks (~> 3.9.0)
20
+ rspec-core (3.9.1)
21
+ rspec-support (~> 3.9.1)
22
+ rspec-expectations (3.9.0)
23
+ diff-lcs (>= 1.2.0, < 2.0)
24
+ rspec-support (~> 3.9.0)
25
+ rspec-mocks (3.9.0)
26
+ diff-lcs (>= 1.2.0, < 2.0)
27
+ rspec-support (~> 3.9.0)
28
+ rspec-support (3.9.1)
29
+
30
+ PLATFORMS
31
+ ruby
32
+
33
+ DEPENDENCIES
34
+ bundler (~> 2.0)
35
+ pry
36
+ rake (~> 10.0)
37
+ rspec (~> 3.0)
38
+ simple_request!
39
+
40
+ BUNDLED WITH
41
+ 2.0.2
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2019 MaJeD BoJaN
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.
@@ -0,0 +1,125 @@
1
+ # SimpleRequest
2
+
3
+ `simple_request` founded to make both `HTTP` and `HTTPS` request simple as it should to be
4
+ ## Installation
5
+
6
+ Add this line to your application's Gemfile:
7
+
8
+ ```ruby
9
+ gem 'simple_request'
10
+ ```
11
+
12
+ And then execute:
13
+
14
+ $ bundle
15
+
16
+ Or install it yourself as:
17
+
18
+ $ gem install simple_request
19
+
20
+ ## Examples
21
+
22
+ #### GET Request
23
+ ```ruby
24
+ request = SimpleRequest.get(url: 'https://api.xxxxx.xxxxxx.com/v1/cities', body: {}, headers: {'API-ACCESSOR' => 'xxxxxxx-xxxxx-xxxx-xxxx-x'})
25
+ request.json
26
+ # OUTPUT
27
+ # {
28
+ # "message"=>"Data found",
29
+ # "cities"=>{
30
+ # "data"=>[
31
+ # {
32
+ # "id"=>"8",
33
+ # "type"=>"city",
34
+ # "attributes"=>{
35
+ # "name_en"=>"Mohali",
36
+ # "status"=>"inactive"
37
+ # }
38
+ # }
39
+ # ]
40
+ # }
41
+ # }
42
+ request.plain
43
+ # OUTPUT
44
+ # "{\"message\":\"Data found\",\"cities\":{\"data\":[{\"id\":\"8\",\"type\":\"city\",\"attributes\":{\"name_en\":\"Mohali\",\"name_ar\":\"موهالي\",\"status\":\"inactive\"}}]},\"pagination\":{\"current_page\":1,\"next_page\":2,\"previous_page\":null,\"total_pages\":6,\"per_page\":1,\"total_entries\":6}}"
45
+
46
+ request.scheme # => "https"
47
+ request.host # => "api.xxxxx.xxxxxx.com"
48
+ request.port # => 80
49
+ request.request_uri # => "/v1/cities?limit=1"
50
+ request.path # => "/v1/cities"
51
+ request.query # => "limit=1"
52
+ ```
53
+
54
+ ### POST Request
55
+ ```ruby
56
+
57
+ request = SimpleRequest.post(
58
+ url: 'https://api.xxxxx.xxxxxx.com/v1/cities',
59
+ body: {"city"=>{"name_ar"=>"المكلا", "name_en"=>"Mukalla", "status"=>"active"}, "locale"=>"en"},
60
+ headers: {"Authorization"=> "Bearer xxxxxxxxxxxx.xxxxxxxx.xxxxxxxx"}
61
+ )
62
+ request.json
63
+ # OUTPUT
64
+ # {"message"=>"City created successfully", "city"=>{"data"=>{"id"=>"10", "type"=>"city_details", "attributes"=>{"name_en"=>"Mukalla", "name_ar"=>"المكلا", "suggested_time"=>0, "suggested"=>false, "status"=>"active"}}}}
65
+ request.plain
66
+ # OUTPUT
67
+ # "{\"message\":\"City created successfully\",\"city\":{\"data\":{\"id\":\"10\",\"type\":\"city_details\",\"attributes\":{\"name_en\":\"Mukalla\",\"name_ar\":\"المكلا\",\"suggested_time\":0,\"suggested\":false,\"status\":\"active\"}}}}"
68
+ ```
69
+
70
+ ### PUT, Patch Request
71
+ ```ruby
72
+
73
+ request = SimpleRequest.put(
74
+ url: 'https://api.xxxxx.xxxxxx.com/v1/cities/10',
75
+ body: {"city"=>{"name_ar"=>"حضرموت", "name_en"=>"Hadramut", "status"=>"active"}, "locale"=>"en"},
76
+ headers: {"Authorization"=> "Bearer xxxxxxxxxxxx.xxxxxxxx.xxxxxxxx"}
77
+ )
78
+
79
+ request = SimpleRequest.patch(
80
+ url: 'https://api.xxxxx.xxxxxx.com/v1/cities/10',
81
+ body: {"city"=>{"name_ar"=>"حضرموت", "name_en"=>"Hadramut", "status"=>"active"}, "locale"=>"en"},
82
+ headers: {"Authorization"=> "Bearer xxxxxxxxxxxx.xxxxxxxx.xxxxxxxx"}
83
+ )
84
+
85
+ request.json
86
+ # OUTPUT
87
+ # {"message"=>"City updated successfully", "city"=>{"data"=>{"id"=>"10", "type"=>"city_details", "attributes"=>{"name_en"=>"Hadramut", "name_ar"=>"حضرموت", "suggested_time"=>0, "suggested"=>false, "status"=>"active"}}}}
88
+ request.plain
89
+ # OUTPUT
90
+ # "{\"message\":\"City updated successfully\",\"city\":{\"data\":{\"id\":\"10\",\"type\":\"city_details\",\"attributes\":{\"name_en\":\"Hadramut\",\"name_ar\":\"حضرموت\",\"suggested_time\":0,\"suggested\":false,\"status\":\"active\"}}}}"
91
+ ```
92
+
93
+ ### DELETE Request
94
+ ```ruby
95
+ request = SimpleRequest.delete(
96
+ url: 'https://api.xxxxx.xxxxxx.com/v1/cities/10',
97
+ body: {},
98
+ headers: {"Authorization"=> "Bearer xxxxxxxxxxxx.xxxxxxxx.xxxxxxxx"}
99
+ )
100
+
101
+ request.json
102
+ # OUTPUT
103
+ # {"message"=>"City deleted successfully", "id"=>10}
104
+ request.plain
105
+ # OUTPUT
106
+ # "{\"message\":\"City deleted successfully\",\"id\":10}"
107
+ ```
108
+
109
+ ## Development
110
+
111
+ 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.
112
+
113
+ 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).
114
+
115
+ ## Contributing
116
+
117
+ Bug reports, pull requests new ideas are welcome on GitHub at [Simple Request Repo](https://github.com/MajedBojan/simple_request). This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct.
118
+
119
+ ## License
120
+
121
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
122
+
123
+ ## Code of Conduct
124
+
125
+ Everyone interacting in the SimpleRequest project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/simple_request/blob/master/CODE_OF_CONDUCT.md).
@@ -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
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "simple_request"
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__)
@@ -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,23 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'constant_data'
4
+
5
+ module SimpleHelper
6
+ class Const
7
+ def self.supported_methods
8
+ ConstantData::SupportedHTTPMethods
9
+ end
10
+
11
+ def self.supported_schemes
12
+ ConstantData::SupportedURISchemes
13
+ end
14
+
15
+ def self.reference
16
+ ConstantData::REFERENCES
17
+ end
18
+
19
+ def self.supported_format
20
+ ConstantData::SUPPORTED_FORMAT
21
+ end
22
+ end
23
+ end
@@ -0,0 +1,18 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SimpleHelper
4
+ class ConstantData
5
+ SupportedHTTPMethods = {
6
+ 'get' => Net::HTTP::Get,
7
+ 'post' => Net::HTTP::Post,
8
+ 'patch' => Net::HTTP::Patch,
9
+ 'put' => Net::HTTP::Put,
10
+ 'delete' => Net::HTTP::Delete
11
+ }.freeze
12
+
13
+ REFERENCES = %w[scheme host port request_uri path query].freeze
14
+ SUPPORTED_FORMAT = %w[json plain].freeze
15
+ # SUPPORTED_FORMAT = %w[xml json csv plain].freeze
16
+ SupportedURISchemes = ['http', 'https'].freeze
17
+ end
18
+ end
@@ -0,0 +1,32 @@
1
+ module SimpleHelper
2
+ class Error < StandardError; end
3
+
4
+ # Exception raised when you attempt to set a non-existent format
5
+ class UnsupportedFormat < Error; end
6
+
7
+ # Exception raised when using a URI scheme other than HTTP or HTTPS
8
+ class UnsupportedURIScheme < Error; end
9
+
10
+ # @abstract Exceptions which inherit from ResponseError contain the Net::HTTP
11
+ # response object accessible via the {#response} method.
12
+ class ResponseError < Error
13
+ # Returns the response of the last request
14
+ # @return [Net::HTTPResponse] A subclass of Net::HTTPResponse, e.g.
15
+ # Net::HTTPOK
16
+ attr_reader :response
17
+
18
+ # Instantiate an instance of ResponseError with a Net::HTTPResponse object
19
+ # @param [Net::HTTPResponse]
20
+ def initialize(response)
21
+ @response = response
22
+ super(response)
23
+ end
24
+ end
25
+
26
+ # Exception that is raised when request has redirected too many times.
27
+ # Calling {#response} returns the Net:HTTP response object.
28
+ class RedirectionTooDeep < ResponseError; end
29
+
30
+ # Exception that is raised when request redirects and location header is present more than once
31
+ class DuplicateLocationHeader < ResponseError; end
32
+ end
@@ -0,0 +1,18 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'pry'
4
+ module SimpleHelper
5
+ module HeadersProcessor
6
+ attr_reader :headers
7
+
8
+ def self.perform(headers)
9
+ return {} if headers.nil? || !headers.respond_to?(:to_hash)
10
+
11
+ @headers = SimpleHelper::Utils.stringify_keys(headers)
12
+
13
+ return @headers unless @headers['Content-Type'].nil?
14
+
15
+ { 'Content-Type' => 'application/json' }.merge(@headers)
16
+ end
17
+ end
18
+ end
@@ -0,0 +1,26 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'uri'
4
+ require 'net/http'
5
+ require_relative 'const'
6
+
7
+ module SimpleHelper
8
+ module Http
9
+ class << self
10
+ SimpleHelper::Const.supported_methods.each do |key, http_method|
11
+ define_method key.to_s do |uri, params, headers|
12
+ http = Net::HTTP.new(uri.host, uri.port)
13
+ req = http_method.new(uri, headers)
14
+ req.body = params.to_json
15
+ http.request(req)
16
+ rescue Timeout::Error || Net::OpenTimeout
17
+ puts "\e[31mTime out!\e[0m"
18
+ rescue Net::HTTPBadResponse || SocketError
19
+ puts "\e[31mRequest Failed!\e[0m"
20
+ rescue StandardError
21
+ puts "\e[31mAn unknown error occurred!\e[0m"
22
+ end
23
+ end
24
+ end
25
+ end
26
+ end
@@ -0,0 +1,28 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'uri'
4
+ require 'net/https'
5
+ require 'pry'
6
+ module SimpleHelper
7
+ module Https
8
+ class << self
9
+ SimpleHelper::Const.supported_methods.each do |key, http_method|
10
+ define_method key.to_s do |uri, params, headers|
11
+ https = Net::HTTP.new(uri.host, uri.port)
12
+ https.use_ssl = true
13
+ https.verify_mode = OpenSSL::SSL::VERIFY_NONE
14
+
15
+ req = http_method.new(uri, headers)
16
+ req.body = params.to_json
17
+ https.request(req)
18
+ rescue Timeout::Error || Net::OpenTimeout
19
+ puts "\e[31mTime out!\e[0m"
20
+ rescue Net::HTTPBadResponse || SocketError
21
+ puts "\e[31mRequest Failed!\e[0m"
22
+ rescue StandardError
23
+ puts "\e[31mAn unknown error occurred!\e[0m"
24
+ end
25
+ end
26
+ end
27
+ end
28
+ end
@@ -0,0 +1,56 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'pry'
4
+
5
+ module SimpleHelper
6
+ class ResponseParser
7
+ attr_reader :body, :format
8
+
9
+ def initialize(body, format)
10
+ @body = body
11
+ @format = format
12
+ end
13
+
14
+ def self.perform(body, format)
15
+ new(body, format).parse
16
+ end
17
+
18
+ def parse
19
+ return nil if body.nil?
20
+ return nil if body == 'null'
21
+ return nil if body.valid_encoding? && body.strip.empty?
22
+
23
+ @body = body.gsub(/\A#{UTF8_BOM}/, '') if body.valid_encoding? && body.encoding == Encoding::UTF_8
24
+ send(format)
25
+ end
26
+
27
+ protected
28
+
29
+ # TODO: Support other formats like xml, csv
30
+
31
+ UTF8_BOM = "\xEF\xBB\xBF"
32
+
33
+ def json
34
+ JSON.parse(body, quirks_mode: true, allow_nan: true)
35
+ rescue JSON::ParserError
36
+ puts "Response cannot be parsed because it's not a string not valid JSON. please use .plain to get the the plain response"
37
+ end
38
+
39
+ def plain
40
+ body
41
+ end
42
+
43
+ # def csv
44
+ # CSV.parse(body)
45
+ # end
46
+ # def xml
47
+ # MultiXml.parse(body)
48
+ # end
49
+
50
+ # def parse_supported_format
51
+ # send(format)
52
+ # rescue NoMethodError => e
53
+ # raise NotImplementedError, "#{self.class.name} has not implemented a parsing method for the #{format.inspect} format.", e.backtrace
54
+ # end
55
+ end
56
+ end
@@ -0,0 +1,48 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SimpleHelper
4
+ module Utils
5
+ def self.stringify_keys(hash)
6
+ return hash.transform_keys(&:to_s) if hash.respond_to?(:transform_keys)
7
+
8
+ hash.each_with_object({}) do |(key, value), new_hash|
9
+ new_hash[key.to_s] = value
10
+ end
11
+ end
12
+
13
+ def self.symbolize_keys(obj)
14
+ case obj
15
+ when Array
16
+ obj.inject([]){|res, val|
17
+ res << case val
18
+ when Hash, Array
19
+ symbolize_keys(val)
20
+ else
21
+ val
22
+ end
23
+ res
24
+ }
25
+ when Hash
26
+ obj.inject({}){|res, (key, val)|
27
+ nkey = case key
28
+ when String
29
+ key.to_sym
30
+ else
31
+ key
32
+ end
33
+ nval = case val
34
+ when Hash, Array
35
+ symbolize_keys(val)
36
+ else
37
+ val
38
+ end
39
+ res[nkey] = nval
40
+ res
41
+ }
42
+ else
43
+ obj
44
+ end
45
+ end
46
+
47
+ end
48
+ end
@@ -0,0 +1,3 @@
1
+ module SimpleHelper
2
+ VERSION = "0.1.1"
3
+ end
@@ -0,0 +1,113 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'uri'
4
+ require 'pry'
5
+ require 'json'
6
+ # require 'net/http'
7
+ # require 'net/https'
8
+
9
+ require_relative 'simple_helper/const'
10
+ require_relative 'simple_helper/http'
11
+ require_relative 'simple_helper/https'
12
+ require_relative 'simple_helper/utils'
13
+ require_relative 'simple_helper/version'
14
+ require_relative 'simple_helper/exceptions'
15
+ require_relative 'simple_helper/response_parser'
16
+ require_relative 'simple_helper/headers_processor'
17
+
18
+ class SimpleRequest
19
+ attr_reader :options, :response
20
+
21
+ def initialize(**options)
22
+ @options = SimpleHelper::Utils.symbolize_keys(options)
23
+ validate
24
+ end
25
+
26
+ # This define method should create ["get", "post", "patch", "put", "delete"] class methods
27
+ class << self
28
+ SimpleHelper::Const.supported_methods.keys.each do |method_name|
29
+ define_method method_name do |*args|
30
+ new(*args).send(method_name)
31
+ end
32
+ end
33
+ end
34
+
35
+ # This define method should create ["get", "post", "patch", "put", "delete"] instance methods
36
+ SimpleHelper::Const.supported_methods.keys.each do |method_name|
37
+ define_method method_name do
38
+ @response = requested_class.send(method_name, uri, body, headers_processor)
39
+ self
40
+ end
41
+ end
42
+
43
+ # This define method should create ["scheme", "host", "port", "request_uri", "path", "query"] instance methods
44
+ SimpleHelper::Const.reference.each do |key|
45
+ define_method key do
46
+ uri.instance_eval(key)
47
+ end
48
+ end
49
+
50
+ SimpleHelper::Const.supported_format.each do |key|
51
+ define_method key do
52
+ SimpleHelper::ResponseParser.perform(body_response, key)
53
+ end
54
+ end
55
+
56
+ private
57
+
58
+ def requested_class
59
+ Object.const_get("SimpleHelper::#{scheme.capitalize}")
60
+ end
61
+
62
+ def body
63
+ options[:body]
64
+ end
65
+
66
+ def body_response
67
+ response&.body
68
+ end
69
+
70
+ def headers_processor
71
+ SimpleHelper::HeadersProcessor.perform(headers)
72
+ end
73
+
74
+ def http_method
75
+ # "#{Net::HTTP::}"
76
+ end
77
+
78
+ def headers
79
+ options[:headers] || {}
80
+ end
81
+
82
+ def uri
83
+ URI(options[:url])
84
+ end
85
+
86
+ def response_processor; end
87
+
88
+ def validate
89
+ # raise SimpleHelper::RedirectionTooDeep.new(last_response), 'HTTP redirects too deep' if options[:limit].to_i <= 0
90
+
91
+ # unless SimpleHelper::Const.supported_methods.include?(http_method)
92
+ # raise ArgumentError, 'only get, post, patch, put, and delete methods are supported'
93
+ # end
94
+
95
+ raise ArgumentError, ':headers must be a hash' unless headers.respond_to?(:to_hash)
96
+
97
+ unless SimpleHelper::Const.supported_schemes.include? scheme
98
+ raise SimpleHelper::UnsupportedURIScheme, ' URL Must start with http:// or https://'
99
+ end
100
+
101
+ # if options[:basic_auth] && !options[:basic_auth].respond_to?(:to_hash)
102
+ # raise ArgumentError, ':basic_auth must be a hash'
103
+ # end
104
+
105
+ # if options[:digest_auth] && !options[:digest_auth].respond_to?(:to_hash)
106
+ # raise ArgumentError, ':digest_auth must be a hash'
107
+ # end
108
+
109
+ # if post? && !options[:query].nil? && !options[:query].respond_to?(:to_hash)
110
+ # raise ArgumentError, ':query must be hash if using HTTP Post'
111
+ # end
112
+ end
113
+ end
Binary file
@@ -0,0 +1,33 @@
1
+ lib = File.expand_path("lib", __dir__)
2
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
3
+ require "simple_helper/version"
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = "simple_request"
7
+ spec.version = SimpleHelper::VERSION
8
+ spec.authors = ["MaJeD BoJaN"]
9
+ spec.email = ["bojanmajed@gmail.com"]
10
+
11
+ spec.summary = %q{Simple ruby gem that helps to make HTTP and HTTPS request from ruby projects.}
12
+ spec.homepage = "https://github.com/MajedBojan/simple_request"
13
+ spec.license = "MIT"
14
+
15
+ # spec.metadata["allowed_push_host"] = "TODO: Set to 'http://mygemserver.com'"
16
+
17
+ spec.metadata["homepage_uri"] = spec.homepage
18
+ spec.metadata["source_code_uri"] = "https://github.com/MajedBojan/simple_request"
19
+ spec.metadata["changelog_uri"] = "https://github.com/MajedBojan/simple_request/blob/master/Changelog.md"
20
+
21
+ # Specify which files should be added to the gem when it is released.
22
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
23
+ spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do
24
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
25
+ end
26
+ spec.bindir = "exe"
27
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
28
+ spec.require_paths = ["lib"]
29
+
30
+ spec.add_development_dependency "bundler", "~> 2.0"
31
+ spec.add_development_dependency "rake", "~> 10.0"
32
+ spec.add_development_dependency "rspec", "~> 3.0"
33
+ end
metadata ADDED
@@ -0,0 +1,114 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: simple_request
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.1
5
+ platform: ruby
6
+ authors:
7
+ - MaJeD BoJaN
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2020-01-23 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: '2.0'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '2.0'
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
+ - !ruby/object:Gem::Dependency
42
+ name: rspec
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '3.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.0'
55
+ description:
56
+ email:
57
+ - bojanmajed@gmail.com
58
+ executables: []
59
+ extensions: []
60
+ extra_rdoc_files: []
61
+ files:
62
+ - ".gitignore"
63
+ - ".rspec"
64
+ - ".rubocop.yml"
65
+ - ".rubocop_todo.yml"
66
+ - ".travis.yml"
67
+ - CODE_OF_CONDUCT.md
68
+ - Changelog.md
69
+ - Gemfile
70
+ - Gemfile.lock
71
+ - LICENSE.txt
72
+ - README.md
73
+ - Rakefile
74
+ - bin/console
75
+ - bin/setup
76
+ - lib/simple_helper/const.rb
77
+ - lib/simple_helper/constant_data.rb
78
+ - lib/simple_helper/exceptions.rb
79
+ - lib/simple_helper/headers_processor.rb
80
+ - lib/simple_helper/http.rb
81
+ - lib/simple_helper/https.rb
82
+ - lib/simple_helper/response_parser.rb
83
+ - lib/simple_helper/utils.rb
84
+ - lib/simple_helper/version.rb
85
+ - lib/simple_request.rb
86
+ - simple_request-0.1.0.gem
87
+ - simple_request.gemspec
88
+ homepage: https://github.com/MajedBojan/simple_request
89
+ licenses:
90
+ - MIT
91
+ metadata:
92
+ homepage_uri: https://github.com/MajedBojan/simple_request
93
+ source_code_uri: https://github.com/MajedBojan/simple_request
94
+ changelog_uri: https://github.com/MajedBojan/simple_request/blob/master/Changelog.md
95
+ post_install_message:
96
+ rdoc_options: []
97
+ require_paths:
98
+ - lib
99
+ required_ruby_version: !ruby/object:Gem::Requirement
100
+ requirements:
101
+ - - ">="
102
+ - !ruby/object:Gem::Version
103
+ version: '0'
104
+ required_rubygems_version: !ruby/object:Gem::Requirement
105
+ requirements:
106
+ - - ">="
107
+ - !ruby/object:Gem::Version
108
+ version: '0'
109
+ requirements: []
110
+ rubygems_version: 3.0.3
111
+ signing_key:
112
+ specification_version: 4
113
+ summary: Simple ruby gem that helps to make HTTP and HTTPS request from ruby projects.
114
+ test_files: []