Class: Reddit::CLI

Inherits:
Object
  • Object
show all
Defined in:
lib/reddit/cli.rb

Instance Method Summary collapse

Instance Method Details

#callObject



2
3
4
5
6
# File 'lib/reddit/cli.rb', line 2

def call
  puts "Here's the current hot list on r/ruby"
  show_posts
  menu
end

#get_score_text(index) ⇒ Object



37
38
39
40
41
42
43
44
45
46
# File 'lib/reddit/cli.rb', line 37

def get_score_text(index)
  post = @posts[index.to_i]
  upvotes = post[:upvotes]
  if post[:upvotes].to_i == 1
    score = post[:upvotes].to_i >= 0 ? 'upvote' : 'downvote'
  else
    score = post[:upvotes].to_i >= 0 ? 'upvotes' : 'downvotes'
  end
  return "#{upvotes} #{score}"
end


18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/reddit/cli.rb', line 18

def menu
  input = nil
  while input != "exit"
    puts ""
    puts "> Enter the number of the post you'd like more info on:"
    input = gets.strip.downcase

    if input.to_i > 0
      show_post(input.to_i-1)
    elsif input == "list"
      show_posts
    elsif input == "exit" || input == "q"
      exit!
    else
      puts "> Not sure what you want, type list or exit."
    end
  end
end

#openInBrowser(url) ⇒ Object



8
9
10
11
12
13
14
15
16
# File 'lib/reddit/cli.rb', line 8

def openInBrowser(url)
  if RbConfig::CONFIG['host_os'] =~ /mswin|mingw|cygwin/
    system "start #{url}"
  elsif RbConfig::CONFIG['host_os'] =~ /darwin/
    system "open #{url}"
  elsif RbConfig::CONFIG['host_os'] =~ /linux|bsd/
    system "xdg-open #{url}"
  end
end

#show_post(index) ⇒ Object



58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/reddit/cli.rb', line 58

def show_post(index)
  post = @posts[index.to_i]
  puts ""
  puts "Title: #{post[:title]}"
  puts "Author: #{post[:author]}"
  puts "Score: #{post[:upvotes]}"
  puts "Comments: #{post[:comments]}"
  puts "Posted: #{post[:timestamp]}"
  puts ""
  input = nil
  while input != "exit"
    puts "> Enter the option you'd like to perform:"
    puts "1. Open in browser"
    puts "2. Show hot posts"
    puts "3. Exit"
    puts ""
    input = gets.strip.downcase
    if input.to_i == 1
      openInBrowser(post[:url])
    elsif input.to_i == 2
      show_posts
      break
    elsif input.to_i == 3 || input == "exit" || input == "q"
      exit!
    else
      puts "> Not sure what you want, type list or exit."
    end
  end
end

#show_postsObject



48
49
50
51
52
53
54
55
56
# File 'lib/reddit/cli.rb', line 48

def show_posts
  Reddit::Scraper.scrape
  @posts = Reddit::Scraper.scrape
  @posts.each_with_index do |post, i|
    upvotes = get_score_text(i)
    index = "#{i + 1}"
    puts "#{index.bold}. #{upvotes} - #{post[:title]} by #{post[:author].bold}"
  end
end