In this guide, we will cover essential concepts and techniques for working with networking and APIs in Ruby, including using Net::HTTP, consuming APIs, and integrating WebSockets into your Ruby applications.
Net::HTTP?
Net::HTTP.get("http://example.com")HTTP.get("http://example.com")get("http://example.com")HTTP::Request.get("http://example.com")OpenURI can be used to retrieve the content of a URL?
opengetfetchretrieveNet::HTTP?
OpenURI in Ruby?
require 'net/http'require 'open-uri'require 'uri'require 'http'Net::HTTP is used for making a POST request?
Net::HTTP.getNet::HTTP.postNet::HTTP.requestNet::HTTP.sendJSON.parse(response)parse_json(response)response.parse_jsonparse(response)Net::HTTP is used to check the response code from an HTTP request?
response.status_coderesponse.coderesponse.resultresponse.response_codeNet::HTTP?
Net::HTTP.sendNet::HTTP.set_dataNet::HTTP.post_formNet::HTTP.postrails-apirack-apiactive_apiaction_controllerAuthorization headerNet::HTTP.set_headersNet::HTTP.add_headerrequest['header_name'] = valuerequest.headers['header_name'] = valueNet::HTTP.post with Content-Type: application/json headerNet::HTTP.get with JSON parametersNet::HTTP.fetchNet::HTTP.json_postwebsocket-rubysocket-iofaye-websockethttp-websocketfaye-websocket gem?
Faye::WebSocket.new('ws://localhost:8080')WebSocket.open('ws://localhost:8080')Net::HTTP.websocket('ws://localhost:8080')Faye::Socket.connect('ws://localhost:8080')on_messagemessage_receivedmessageon_datafaye-websocket gem?
socket.send("Hello!")socket.send_message("Hello!")socket.write("Hello!")socket.emit("Hello!")socket.closesocket.shutdownsocket.disconnectsocket.terminateon_error event handlerbegin-rescueon_exception| Qno | Answer |
|---|---|
| 1 | a) Net::HTTP |
| 2 | a) Net::HTTP.get("http://example.com") |
| 3 | c) OpenURI |
| 4 | a) open |
| 5 | a) By including them in the URL |
| 6 | b) require 'open-uri' |
| 7 | b) Net::HTTP.post |
| 8 | a) JSON.parse(response) |
| 9 | b) response.code |
| 10 | d) Net::HTTP.post |
| 11 | b) Sending a request to the API |
| 12 | d) action_controller |
| 13 | b) By using the Authorization header |
| 14 | a) Raise an exception |
| 15 | c) JSON |
| 16 | b) GET |
| 17 | a) 200 |
| 18 | d) request.headers['header_name'] = value |
| 19 | a) Retry after a set amount of time |
| 20 | a) Net::HTTP.post with Content-Type: application/json header |
| 21 | a) To establish a two-way communication between a client and server |
| 22 | c) faye-websocket |
| 23 | c) WebSocket Protocol (ws:// or wss://) |
| 24 | a) Faye::WebSocket.new('ws://localhost:8080') |
| 25 | a) on_message |
| 26 | a) socket.send("Hello!") |
| 27 | a) socket.close |
| 28 | a) By using the on_error event handler |
| 29 | a) To send real-time data to clients |
| 30 | b) WebSockets allow full-duplex communication |