Class: Lita::Handlers::OnewheelAmazonProduct

Inherits:
Handler
  • Object
show all
Defined in:
lib/lita/handlers/onewheel_amazon_product.rb

Instance Method Summary collapse

Instance Method Details

#get_amazon_product(response) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/lita/handlers/onewheel_amazon_product.rb', line 9

def get_amazon_product(response)
  description = ''
  price = 0
  uri = response.matches[0][0]
  Lita.logger.debug "lita-onewheel-amazon-product: Grabbing URI #{uri}"
  doc = RestClient.get uri

  noko_doc = Nokogiri::HTML doc
  noko_doc.css('meta').each do |meta|
    attrs = meta.attributes
    if attrs['name'].to_s == 'title'
      description = process_description attrs['content'].to_s
    end
  end

  if description.empty?
    Lita.logger.error "lita-onewheel-amazon-product: Processing of #{uri} failed."
    return
  end

  price = get_price(noko_doc)

  unless description.empty?
    response.reply price.to_s + ' ' + description.to_s
  end
end

#get_price(noko_doc) ⇒ Object

Getting prices is very non-intuitive, every type of price has it’s own structure. Here we keep trying until we get something.



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/lita/handlers/onewheel_amazon_product.rb', line 38

def get_price(noko_doc)
  price_node = noko_doc.css('span#priceblock_ourprice')

  # Typical product price
  if price_node.empty?
    price_node = noko_doc.css('div#unqualifiedBuyBox .a-color-price')
  end

  # Third-party seller only price
  if price_node.empty?
    price_node = noko_doc.css('div#buyNewSection span.a-color-price')
  end

  # Kindle book price
  if price_node.empty?
    price_node = noko_doc.css('td.dp-price-col span.a-color-price')
  end

  unless price_node.empty?
    price = price_node.first.content.to_s
  end
  price
end

#process_description(desc) ⇒ Object



62
63
64
65
# File 'lib/lita/handlers/onewheel_amazon_product.rb', line 62

def process_description(desc)
  desc.sub! /^Amazon.com\s*: /, ''
  desc.sub! /:.*$/, ''
end