Module: TrickOrTreat

Extended by:
TrickOrTreat
Included in:
TrickOrTreat
Defined in:
lib/trick_or_treat.rb,
lib/trick_or_treat/version.rb

Defined Under Namespace

Classes: Error

Constant Summary collapse

VERSION =
"0.2.3"

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#treat_fileObject

Returns the value of attribute treat_file.



12
13
14
# File 'lib/trick_or_treat.rb', line 12

def treat_file
  @treat_file
end

#uriObject

Returns the value of attribute uri.



12
13
14
# File 'lib/trick_or_treat.rb', line 12

def uri
  @uri
end

Instance Method Details

#ask(args = []) ⇒ Object



17
18
19
20
21
22
23
# File 'lib/trick_or_treat.rb', line 17

def ask(args=[])
  printf "\e[1;38;05;202mTrick or Treat? "
  no_candy if Gem.win_platform?
  return trick if args.delete('trick')
  return treat if args.delete('treat')
  no_candy
end


37
38
39
40
# File 'lib/trick_or_treat.rb', line 37

def get_links
  nodes=Nokogiri::HTML(open(uri)).css('a')
  nodes.map{|n| n['href'] if  n.attributes['class'].value.match /trick/i}.compact
end

#no_candyObject



66
67
68
# File 'lib/trick_or_treat.rb', line 66

def no_candy
  return "\e[1;38;05;165mNo candy for you\e[0m"
end

#tempfile(headers = {}) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
# File 'lib/trick_or_treat.rb', line 25

def tempfile(headers={})
  stream = open([uri,treat_file].join('/'), "rb", headers)
  return stream if stream.respond_to?(:path)

  Tempfile.new.tap do |file|
    file.binmode
    IO.copy_stream(stream, file)
    stream.close
    file.rewind
  end
end

#treatObject



55
56
57
58
59
60
61
62
63
64
# File 'lib/trick_or_treat.rb', line 55

def treat
  printf "\e[1;38;05;165mTreat\e[0m\n"
  headers={}
  headers={'user-agent' => 'treat'}
  treats=YAML.load_file(tempfile(headers))
  treats[treats.keys.sample].values.sample
rescue OpenURI::HTTPError => e
  response=e.io
  response.string
end

#trickObject



42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/trick_or_treat.rb', line 42

def trick
  puts "\e[1;38;05;165mTrick\e[0m"
  links=get_links
  link=links.sample
  f=open([uri,link].join('/'))
  html=Nokogiri::HTML(f)
  puts title=html.css('h1').text.gsub(/  +|\n/, '')
  content=html.css('.post-content')
  IO.popen("less", "w") do |f|
     f.puts "\e[1m#{title}\e[0m\n#{content.text}"
  end
end