Class: Tronscan::Api

Inherits:
Object
  • Object
show all
Defined in:
lib/tronscan/api.rb

Instance Method Summary collapse

Constructor Details

#initialize(url, api_key = nil) ⇒ Api

Returns a new instance of Api.



3
4
5
6
# File 'lib/tronscan/api.rb', line 3

def initialize(url, api_key = nil)
  @url = url
  @api_key = api_key
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args) ⇒ Object



38
39
40
41
# File 'lib/tronscan/api.rb', line 38

def method_missing(method, *args)
  module_name, action = method.to_s.split('_')
  request(module_name, action, args[0] || {})
end

Instance Method Details

#request(module_name, action = nil, params = {}) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/tronscan/api.rb', line 8

def request(module_name, action = nil, params = {})
  action_path = action.nil? ? '' : "/#{action}"

  params = params.reject { |_k, v| v.nil? } # filter out nil values
  params_query = params.keys.map { |key| "#{key}=#{params[key]}" }.join('&').strip
  params_query = '' if params_query.empty?

  uri = URI "#{@url}/#{module_name}#{action_path}?#{params_query}"
  Etherscan.logger.debug "Req: #{uri}"

  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = (uri.scheme == 'https')

  request = Net::HTTP::Get.new(uri.request_uri)
  request['TRON-PRO-API-KEY'] = @api_key unless @api_key.nil?

  response = http.request(request)
  # Etherscan.logger.debug "Rsp: #{resp}"
  raise response.body if response.code != '200'

  JSON.parse(response.body)
rescue StandardError => e
  puts e.message
  puts e.backtrace.inspect
end

#respond_to_missing?(*_args) ⇒ Boolean

Returns:

  • (Boolean)


34
35
36
# File 'lib/tronscan/api.rb', line 34

def respond_to_missing?(*_args)
  true
end