class StockQuote::Stock

> StockQuote::Stock

Queries IEX for current and historical pricing.

Constants

ATTRIBUTION
RANGES
TYPES
URL
VERSION

Attributes

api_key[RW]
attribution[RW]
response_code[RW]

Public Class Methods

create_method(name) click to toggle source
# File lib/stock_quote/stock.rb, line 21
def create_method(name)
  self.class.instance_eval do
    define_method(name) {|symbol, range=nil| batch(name, symbol, range) }
    define_method("raw_#{name}") {|symbol, range=nil| batch(name, symbol, range, 'json') }
  end
end
new(data={}) click to toggle source
# File lib/stock_quote/stock.rb, line 37
def initialize(data={})
  self.class.api_key = data.delete(:api_key) if !!(data[:api_key])
  data.each {|k,v|
    self.class.__send__(:attr_accessor, Util.underscore(k).to_sym)
    self.instance_variable_set("@#{Util.underscore(k)}".to_sym, v)
  }
  @attribution = ATTRIBUTION
  @response_code = !!([{}, nil, ''].include?(data)) ? 500 :  200
end

Protected Class Methods

batch(type, symbol, range=nil,fmt=false) click to toggle source
# File lib/stock_quote/stock.rb, line 59
def self.batch(type, symbol, range=nil,fmt=false)
  raise "Type and symbol required" unless type && symbol
  url =  batch_url(type, symbol, range)
  return request(url, fmt)
end
batch_url(types, symbols, range) click to toggle source
# File lib/stock_quote/stock.rb, line 47
def self.batch_url(types, symbols, range)
  symbols = symbols.is_a?(Array) ? symbols : symbols.split(",")
  types = types.is_a?(Array) ? types : types.split(",")
  if !(['dividends', 'splits'] & types).empty?
    raise "#{types.join(",")} requires a Range: #{RANGES.join(", ")}" unless RANGES.include?(range)
    range = RANGES.include?(range) ? range : nil
  end
  arr = [['token', self.api_key],['symbols', symbols.join(',')], ['types', types.map{|t| t.gsub("_", "-")}.join(',')]]
  arr.push(['range', range]) if !!(range)
  return "#{URL}market/batch?#{URI.encode_www_form(arr)}"
end
request(url, fmt, results=[]) click to toggle source
# File lib/stock_quote/stock.rb, line 65
def self.request(url, fmt, results=[])
  RestClient::Request.execute(:url =>  url, :method => :get, :verify_ssl => false) do |response|
    raise response.body unless response.code == 200
    json = JSON.parse(response)
    return json if fmt=='json'
    results = json.map do |symbol, types|
      result = {}
      types.map do |type, res|
        if res.is_a?(Array)
          result[type.gsub("-", "_")] = res
        else
          res.map{|k,v| result[k] = v }
        end
        result['symbol'] ||= symbol
      end
      Stock.new(result)
    end
  end
  return results.length > 1 ? results : results.shift
end