Sha256: 86b08360e74481374d04cda557674065aa75e18ac1d984c8cbe9267abd98ce4e

Contents?: true

Size: 1.25 KB

Versions: 6

Compression:

Stored size: 1.25 KB

Contents

module Imdb
  
  # Search IMDB for a title
  class Search < MovieList
    attr_reader :query

    # Initialize a new IMDB search with the specified query
    #
    #   search = Imdb::Search.new("Star Trek")
    #
    # Imdb::Search is lazy loading, meaning that unless you access the +movies+ 
    # attribute, no query is made to IMDB.com.
    #
    def initialize(query)
      @query = query
    end
    
    # Returns an array of Imdb::Movie objects for easy search result yielded.
    # If the +query+ was an exact match, a single element array will be returned.
    def movies
      @movies ||= (exact_match? ? parse_movie : parse_movies)
    end
    
    private
    def document
      @document ||= Hpricot(Imdb::Search.query(@query))
    end
    
    def self.query(query)
      open("http://www.imdb.com/find?q=#{CGI::escape(query)};s=tt")
    end
    
    def parse_movie
      id = document.at("head/link[@rel='canonical']")['href'][/\d+/]
      title = document.at("h1").innerHTML.split('<span').first.strip.imdb_unescape_html
      [Imdb::Movie.new(id, title)]
    end
    
    # Returns true if the search yielded only one result, an exact match
    def exact_match?
      !document.at("//h3[text()^='Overview']/..").nil?
    end
    
  end # Search
end # Imdb

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
imdb-0.6.5 lib/imdb/search.rb
imdb-0.6.4 lib/imdb/search.rb
imdb-0.6.3 lib/imdb/search.rb
imdb-0.6.2 lib/imdb/search.rb
imdb-0.6.1 lib/imdb/search.rb
imdb-0.6.0 lib/imdb/search.rb