class CurrentAstronauts::Astronauts
Attributes
data[R]
Public Class Methods
new()
click to toggle source
# File lib/current_astronauts.rb, line 9 def initialize if ENV['OPEN_NOTIFY_URL'] @url = ENV['OPEN_NOTIFY_URL'] else @url = 'http://api.open-notify.org/astros.json' end @data = nil end
Public Instance Methods
fetch()
click to toggle source
Let's go get some data
# File lib/current_astronauts.rb, line 19 def fetch response = HTTParty.get(@url) if response.success? @data = response.parsed_response end response.code end
num()
click to toggle source
How many astronauts in space?
# File lib/current_astronauts.rb, line 37 def num success? ? @data['number'] : nil end
people()
click to toggle source
List of astronauts and their craft, as an array of hashes
# File lib/current_astronauts.rb, line 42 def people success? ? @data['people'] : nil end
print()
click to toggle source
Print a formatted list of astronauts and their craft
# File lib/current_astronauts.rb, line 47 def print unless success? return nil end nlen = "Name".length clen = "Craft".length @data['people'].each do |p| nlen = p['name'].length > nlen ? p['name'].length : nlen clen = p['craft'].length > clen ? p['craft'].length : clen end print_header(nlen, clen) @data['people'].each do |p| print_line(nlen, p['name'], clen, p['craft']) end end
success?()
click to toggle source
Fetch succeeded and data message is 'success'
# File lib/current_astronauts.rb, line 28 def success? stat = false if @data and @data['message'] == 'success' stat = true end return stat end
Private Instance Methods
print_header(nlen, clen)
click to toggle source
print header with appropriate spacing
# File lib/current_astronauts.rb, line 67 def print_header(nlen, clen) print_line(nlen, "Name", clen, "Craft") puts "%-#{nlen}s-|-%-#{clen}s-" % ["-" * nlen, "-" * clen] end
print_line(nlen, n, clen, c)
click to toggle source
print individual lines with appropriate spacing
# File lib/current_astronauts.rb, line 73 def print_line(nlen, n, clen, c) puts "%-#{nlen}s | %-#{clen}s " % [n, c] end