Class: FilmAffinity::Top

Inherits:
Object
  • Object
show all
Defined in:
lib/filmaffinity/top.rb

Overview

Class Top

Instance Method Summary collapse

Constructor Details

#initialize(options: {}, limit: 30) ⇒ Top

Returns a new instance of Top.



4
5
6
7
8
# File 'lib/filmaffinity/top.rb', line 4

def initialize(options: {}, limit: 30)
  @options = options
  @limit = limit
  @json_parser = JsonMoviesParser.new
end

Instance Method Details

#collect_from(collection = [], from = 0, &block) ⇒ Object



41
42
43
44
45
46
# File 'lib/filmaffinity/top.rb', line 41

def collect_from(collection = [], from = 0, &block)
  response = yield(from)
  collection += response
  last_position = collection.size
  response.empty? || last_position >= @limit ? collection.flatten[0..@limit - 1] : collect_from(collection, last_position, &block)
end

#document_html(from) ⇒ Object



14
15
16
# File 'lib/filmaffinity/top.rb', line 14

def document_html(from)
  @document_html = Nokogiri::HTML(generate_html(from))
end

#generate_html(from) ⇒ Object



18
19
20
21
22
23
# File 'lib/filmaffinity/top.rb', line 18

def generate_html(from)
  params = { 'from' => from }
  url = URI.parse(Constants.urls[:top] % query_options)
  data = Net::HTTP.post_form(url, params)
  data.body
end

#moviesObject



10
11
12
# File 'lib/filmaffinity/top.rb', line 10

def movies
  @movies = movies_with_limit
end

#movies_with_limitObject



34
35
36
37
38
39
# File 'lib/filmaffinity/top.rb', line 34

def movies_with_limit
  collect_from do |from|
    doc_obj = document_html from
    parse_movies doc_obj
  end
end

#parse_movies(document_html) ⇒ Object



48
49
50
51
52
53
54
55
56
57
# File 'lib/filmaffinity/top.rb', line 48

def parse_movies(document_html)
  movies = []
  document_html.search('.movie-card.movie-card-0').each_with_index do |movie_card, _index|
    id = movie_card['data-movie-id'].to_i
    title = movie_card.search('.mc-title a').first.content.strip
    movie = FilmAffinity::Movie.new id, title
    movies << movie
  end
  movies
end

#query_optionsObject



25
26
27
28
29
30
31
32
# File 'lib/filmaffinity/top.rb', line 25

def query_options
  query_options = ''
  query_options += '?'
  @options.each do |key, value|
    query_options += Constants.query_params[key] % value
  end
  query_options.gsub(/\&$/, '')
end

#to_jsonObject



59
60
61
# File 'lib/filmaffinity/top.rb', line 59

def to_json
  @json_parser.to_json movies
end