Module: Lolcat

Defined in:
lib/can-has-lolcat.rb

Constant Summary collapse

PROTOCOL =
"http://"
RANDOM =
"icanhascheezburger.com/?random"

Class Method Summary collapse

Class Method Details

.can_has(format = :url, animal = :cat) ⇒ Object Also known as: can_haz



8
9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/can-has-lolcat.rb', line 8

def can_has(format=:url, animal=:cat)

  lol = Lolcat.random_from_internetz(animal)

  case format
  when :html
    "<img src='#{lol}' alt='' />"
  when :bbcode
    "[img]#{lol}[/img]"
  else
    lol
  end
end

.extract_image_url(animal, html) ⇒ Object



45
46
47
48
49
50
51
52
53
# File 'lib/can-has-lolcat.rb', line 45

def extract_image_url(animal, html)
  # is this a kitteh or a puppeh?
  domain = (animal == :dog) ?  "ihasahotdog" : "icanhascheezburger"

  # Find the image URL in the html
  m = html.match(/"http:\/\/#{domain}\.files\.wordpress\.com\/[^"]+/)

  m ? m[0][1..-1] : nil
end

.get_html(url) ⇒ Object

Isolated for easy stubbing during testing



25
26
27
# File 'lib/can-has-lolcat.rb', line 25

def get_html(url)
  open(url).read
end

.random_from_internetz(animal) ⇒ Object



55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/can-has-lolcat.rb', line 55

def random_from_internetz(animal)
  url = nil

  # We shouldn't ever get nil back from random_html with the
  # check for videos in place, but the check is kind of hacky
  # so as a extra precaution we'll check for nil here.
  begin
    url = extract_image_url(animal, random_html(animal))
  end while url.nil?

  url
end

.random_html(animal) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/can-has-lolcat.rb', line 29

def random_html(animal)
  # do they want a kitteh or a puppeh?
  domain = (animal == :dog) ? "dogs." : ""

  # The site randomly returns a video based page at a
  # rate that anecdotally appears to be 15-20% of the
  # time. Detect those links from the title and go
  # back until we get a normal image page.
  html = ""
  begin
    html = get_html(PROTOCOL + domain + RANDOM)
  end while(html.match(/<title>\s+(Video|VIDEO):/))

  html
end