Class: Coinstack::List

Inherits:
Object
  • Object
show all
Defined in:
lib/coinstack/list.rb

Overview

Object for reading and writing our list

Constant Summary collapse

PAIRS_URI =
URI('https://api.coinmarketcap.com/v1/ticker/')
DEFAULT_LOCATION =
(File.dirname(__FILE__) + '/.coinstack-pairs').freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeList

Returns a new instance of List.



16
17
18
19
20
21
# File 'lib/coinstack/list.rb', line 16

def initialize
  self.pairs = {}
  update_pairs!
  FileUtils.touch(DEFAULT_LOCATION) # Ensures it exists
  self.user_pairs = YAML.load_file(DEFAULT_LOCATION) || {}
end

Instance Attribute Details

#pairsObject

hash of hashes like { btc: {}, ltc: {} }



10
11
12
# File 'lib/coinstack/list.rb', line 10

def pairs
  @pairs
end

#user_pairsObject

hash of hashes like { btc: {}, ltc: {} }



10
11
12
# File 'lib/coinstack/list.rb', line 10

def user_pairs
  @user_pairs
end

Instance Method Details

#add(info) ⇒ Object



32
33
34
35
36
37
# File 'lib/coinstack/list.rb', line 32

def add(info)
  data = {}
  data[info[:symbol]] = info[:amount]
  user_pairs.merge!(data)
  save!
end

#remove(symbol) ⇒ Object



39
40
41
42
# File 'lib/coinstack/list.rb', line 39

def remove(symbol)
  user_pairs.delete(symbol)
  save!
end

#save!Object



44
45
46
# File 'lib/coinstack/list.rb', line 44

def save!
  File.open(DEFAULT_LOCATION, 'w') { |f| f.write user_pairs.to_yaml }
end

#update_pairs!Object



23
24
25
26
27
28
29
30
# File 'lib/coinstack/list.rb', line 23

def update_pairs!
  res = Net::HTTP.get_response(PAIRS_URI)
  raise "Could not update pairs! #{res.code}" unless res.is_a?(Net::HTTPSuccess)
  raw_array = JSON.parse(res.body)
  raw_array.each do |data|
    pairs[data['symbol']] = data
  end
end