Class: ScaleRb::HttpClient
- Inherits:
-
Object
- Object
- ScaleRb::HttpClient
- Includes:
- ClientShare
- Defined in:
- lib/scale_rb/client/http_client.rb
Instance Attribute Summary collapse
-
#supported_methods ⇒ Object
Returns the value of attribute supported_methods.
Instance Method Summary collapse
-
#initialize(url) ⇒ HttpClient
constructor
A new instance of HttpClient.
- #method_missing(method, *args) ⇒ Object
- #request(method, params = []) ⇒ Object
- #respond_to_missing?(*_args) ⇒ Boolean
Methods included from ClientShare
Constructor Details
#initialize(url) ⇒ HttpClient
Returns a new instance of HttpClient.
14 15 16 17 18 19 20 21 |
# File 'lib/scale_rb/client/http_client.rb', line 14 def initialize(url) # check if the url is started with http or https url_regex = %r{^https?://} raise 'url format is not correct' unless url.match?(url_regex) @uri = URI.parse(url) @supported_methods = request('rpc_methods', [])[:methods] end |
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(method, *args) ⇒ Object
52 53 54 |
# File 'lib/scale_rb/client/http_client.rb', line 52 def method_missing(method, *args) request(method.to_s, args) end |
Instance Attribute Details
#supported_methods ⇒ Object
Returns the value of attribute supported_methods.
12 13 14 |
# File 'lib/scale_rb/client/http_client.rb', line 12 def supported_methods @supported_methods end |
Instance Method Details
#request(method, params = []) ⇒ Object
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
# File 'lib/scale_rb/client/http_client.rb', line 23 def request(method, params = []) # don't check for rpc_methods, because there is no @supported_methods when initializing if method != 'rpc_methods' && !@supported_methods.include?(method) raise "Method `#{method}` is not supported. It should be in [#{@supported_methods.join(', ')}]." end http = Net::HTTP.new(@uri.host, @uri.port) http.use_ssl = @uri.scheme == 'https' request = Net::HTTP::Post.new(@uri, 'Content-Type' => 'application/json') request.body = { jsonrpc: '2.0', method:, params:, id: Time.now.to_i }.to_json ScaleRb.logger.debug "—→ #{request.body}" # https://docs.ruby-lang.org/en/master/Net/HTTPResponse.html response = http.request(request) raise response unless response.is_a?(Net::HTTPOK) # parse response, make key symbol body = JSON.parse(response.body, symbolize_names: true) ScaleRb.logger.debug "←— #{body}" raise body[:error] if body[:error] body[:result] end |
#respond_to_missing?(*_args) ⇒ Boolean
48 49 50 |
# File 'lib/scale_rb/client/http_client.rb', line 48 def respond_to_missing?(*_args) true end |