class Alphavantage::Client

Attributes

params[R]

Public Class Methods

get(params:, datatype: :json) click to toggle source
# File lib/alphavantage/client.rb, line 9
def get(params:, datatype: :json)
  new(params).public_send(datatype)
end
new(params) click to toggle source
# File lib/alphavantage/client.rb, line 14
def initialize params
  @params = params
end

Public Instance Methods

csv() click to toggle source
# File lib/alphavantage/client.rb, line 25
def csv
  CSV.parse response.body
rescue CSV::MalformedCSVError
  # if we can not parse it, we probably have JSON from API with an error
  json
  raise
end
json() click to toggle source
# File lib/alphavantage/client.rb, line 19
def json
  Hashie::Mash.new(convert_hash_keys(JSON.parse(response.body))).tap do |response|
    raise Error, response.error_message if response.error_message
  end
end

Private Instance Methods

convert_hash_keys(value) click to toggle source
# File lib/alphavantage/client.rb, line 35
def convert_hash_keys(value)
  case value
    when Array
      value.map { |v| convert_hash_keys(v) }
    when Hash
      Hash[value.map { |k, v| [ NormalizeKey.new(key: k).call, convert_hash_keys(v) ] }]
    else
      value
    end
end
default_params() click to toggle source
# File lib/alphavantage/client.rb, line 56
def default_params
  {
    apikey: Alphavantage.configuration.api_key || raise("Api key is missing")
  }
end
response() click to toggle source
# File lib/alphavantage/client.rb, line 46
def response
  @response ||= Faraday.get('https://www.alphavantage.co/query') do |req|
    req.params = default_params.merge(params)
  end.tap do |response|
    next if response.status == 200

    raise Error, "Response status: #{response.status}, body: #{response.body}"
  end
end