Skip to content

Instantly share code, notes, and snippets.

@elliotcm
Created March 6, 2011 19:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elliotcm/857585 to your computer and use it in GitHub Desktop.
Save elliotcm/857585 to your computer and use it in GitHub Desktop.
Get the top 10 films in your Movies folder ranked by IMDB rating. It ain't pretty, but it works.
require 'rubygems'
require 'nokogiri'
require 'open-uri'
class IMDBRank
def self.rank(directory, number_to_return=10)
Dir["#{File.expand_path(directory)}/*.{avi,mp4,m4v}"].sort.map do |filepath|
File.basename(filepath) =~ /(.*?)(?:\s+.(\d{4}).)?\....$/
new($1, $2)
end.reject { |film| film.score.nil? }.
sort_by { |film| film.score }.
reverse.
first(number_to_return).
each do |film|
puts "#{film.score} #{film.name}"
end
end
BASE_URL = "http://www.imdb.com"
SEARCH_URL = BASE_URL + '/find?s=tt&q='
def initialize(name, year=nil)
@name = name
print "Checking score for #{name}#{" [#{year}]" if year}... "
$stdout.flush
@current_page = Nokogiri::HTML(open(URI.escape(SEARCH_URL+"#{name} #{year}")))
if score.nil?
@current_page = Nokogiri::HTML(open(first_result_url)) unless first_result_url.nil?
end
puts score
end
attr_reader :name
def score
elements = @current_page.css('.rating-rating')
return nil if elements.empty?
@current_page.css('.rating-rating').first.text.sub('/10', '').to_f
end
protected
def first_result_url
return nil if first_result_elements.empty?
@first_result_url ||= BASE_URL+first_result_elements.first['href']
end
def first_result_elements
@first_result_elements ||= @current_page.css('#main table:nth-of-type(2) tr:nth-of-type(1) td:nth-of-type(3) a:nth-of-type(1)')
end
end
IMDBRank.rank('~/Movies')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment