Created
August 13, 2011 14:21
-
-
Save jdriscoll/1143901 to your computer and use it in GitHub Desktop.
Silly-simple Amazon price watching script in Ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'open-uri' | |
require 'hpricot' | |
MINUTES_BETWEEN_CHECKS = 15 | |
URLS = ['http://www.amazon.com/Programming-Ruby-1-9-Pragmatic-Programmers/dp/1934356085/', | |
'http://www.amazon.com/Ultimate-Hitchhikers-Guide-Galaxy/dp/0345453743/'] | |
HISTORY_COUNT = 50 | |
CURRENT_PRICE_ELEMENT = '.priceLarge' | |
prices = {} | |
start_time = Time.now | |
# http://stackoverflow.com/questions/4136248/how-to-generate-a-human-readable-time-range-using-ruby-on-rails | |
def humanize secs | |
[[60, :seconds], [60, :minutes], [24, :hours], [1000, :days]].map{ |count, name| | |
if secs > 0 | |
secs, n = secs.divmod(count) | |
"#{n.to_i} #{name}" | |
end | |
}.compact.reverse.join(' ') | |
end | |
while true | |
run_time_seconds = Time.now - start_time | |
puts "-" * 80 | |
puts "\n" | |
puts "Performing check at #{ Time.now.to_s }, running for #{humanize run_time_seconds}" | |
URLS.each do |url| | |
doc = open(url) { |f| Hpricot(f) } | |
price_string = doc.search(CURRENT_PRICE_ELEMENT).inner_html | |
puts "\nItem: #{doc.search('title').inner_html}\nCurrent Price: #{price_string}\n" | |
if prices.has_key?(url) | |
prices[url].unshift(Float(price_string.gsub('$', ''))) | |
else | |
prices[url] = [Float(price_string.gsub('$', ''))] | |
end | |
if (prices.length > HISTORY_COUNT) | |
prices[url].pop | |
end | |
puts "History: " + prices[url][0...HISTORY_COUNT].join(', ') + " ..." | |
end | |
puts "\nNext check in #{MINUTES_BETWEEN_CHECKS} minutes..." | |
puts "\n" | |
sleep(60 * MINUTES_BETWEEN_CHECKS) | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment