Sha256: 6f4a3165af9d476c626ee2598cb3826615f2e21a33af6c13e5f8a0d149dda03b

Contents?: true

Size: 1.24 KB

Versions: 3

Compression:

Stored size: 1.24 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("a[@name='poster']")['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

3 entries across 3 versions & 2 rubygems

Version Path
cschiewek-imdb-0.5.1 lib/imdb/search.rb
imdb-0.5.1 lib/imdb/search.rb
imdb-0.5.0 lib/imdb/search.rb