Sha256: 714df45e45383ae01b0eb70e885154f25cce319789ed2358b1b92d3412f5fbcd

Contents?: true

Size: 1.26 KB

Versions: 1

Compression:

Stored size: 1.26 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://akas.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("//table[@id='title-overview-widget-layout']").nil?
    end
    
  end # Search
end # Imdb

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
imdb-0.6.6 lib/imdb/search.rb