patternrubyMinor
Two HTTP notification methods
Viewed 0 times
methodstwohttpnotification
Problem
I have two very similar methods, which make HTTP requests, the difference is that one makes PUT and another GET. Is there any proper Ruby way not to repeat the setup code and not to pass the flag parameter?
def notify_client(url, params)
uri = URI.parse(url)
https = Net::HTTP.new(uri.host, uri.port)
https.use_ssl = !Rails.env.development?
req = Net::HTTP::Patch.new(uri.path)
req.body = {data: {attributes: params}}.to_json
res = https.request(req)
puts "Response #{res.code} #{res.message}: #{res.body}"
end
def notify_vendor(url, params)
uri = URI.parse(url)
https = Net::HTTP.new(uri.host, uri.port)
https.use_ssl = !Rails.env.development?
req = Net::HTTP::Get.new(uri.path)
req.body = {data: {attributes: params}}.to_json
res = https.request(req)
puts "Response #{res.code} #{res.message}: #{res.body}"
endSolution
In such cases I try to move repeated code to separate method that accepts block.
That code refactoring quite simple. If you need more details - let me know.
def notify_client(url, params)
notify(url, params) { |path| Net::HTTP::Patch.new(path) }
end
def notify_vendor(url, params)
notify(url, params) { |path| Net::HTTP::Get.new(path) }
end
def notify(url, params)
uri = URI.parse(url)
https = Net::HTTP.new(uri.host, uri.port)
https.use_ssl = !Rails.env.development?
req = yield uri.path
req.body = {data: {attributes: params}}.to_json
res = https.request(req)
puts "Response #{res.code} #{res.message}: #{res.body}"
endThat code refactoring quite simple. If you need more details - let me know.
Code Snippets
def notify_client(url, params)
notify(url, params) { |path| Net::HTTP::Patch.new(path) }
end
def notify_vendor(url, params)
notify(url, params) { |path| Net::HTTP::Get.new(path) }
end
def notify(url, params)
uri = URI.parse(url)
https = Net::HTTP.new(uri.host, uri.port)
https.use_ssl = !Rails.env.development?
req = yield uri.path
req.body = {data: {attributes: params}}.to_json
res = https.request(req)
puts "Response #{res.code} #{res.message}: #{res.body}"
endContext
StackExchange Code Review Q#129369, answer score: 6
Revisions (0)
No revisions yet.