Last active
June 17, 2018 02:36
-
-
Save derwiki/67ed523ce83c6e42e017b79dba250fb8 to your computer and use it in GitHub Desktop.
Threaded Net::HTTP::Post service object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'net/http' | |
README = <<-EOS | |
posts = [ | |
{ | |
url: 'https://localhost:3000/', | |
body: '{"status": "OK", "id": 1}' | |
}, | |
{ | |
url: 'https://localhost:3000/', | |
body: '{"status": "OK", "id": 2}' | |
}, | |
] | |
ThreadedPost.new(posts).run do |post, resp| | |
MailRecord.create!(post: post, resp: resp) | |
end | |
EOS | |
class ThreadedPost | |
attr_accessor :posts | |
# post { | |
# url: str, | |
# headers: hash[str, str], | |
# payload: str, | |
# } | |
def initialize(posts) | |
self.posts = posts | |
end | |
def run | |
self.posts.map do |posts| | |
Thread.new do | |
perform_http_request!(post) { yield if block_given? } | |
end | |
end.map(&:join).map(&:value) | |
end | |
def perform_http_request!(post) | |
url = post[:url] | |
uri = URI(url) | |
unless %w(http https).include?(uri.scheme) | |
fail "URL must be http or https: #{url}" | |
end | |
http = Net::HTTP.new(uri.host, uri.port) | |
http.use_ssl = uri.scheme == 'https' | |
req = Net::HTTP::Post.new(uri) | |
headers = post[:headers] || {} | |
headers.each {|k, v| req[k] = v} | |
req.body = post[:payload] | |
resp = http.request(req) | |
yield(:post, :resp) if block_given? | |
[post, resp] | |
rescue => e | |
fail({ | |
exception: "#{e.class}: #{e.message}", | |
url: self.url, | |
payload: payload, | |
headers: self.headers | |
}.to_s) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment