Advertisement
Guest User

Untitled

a guest
Apr 28th, 2017
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rails 1.73 KB | None | 0 0
  1. module Fetching
  2.   class ClubsFetcher < InfoFetcher
  3.     URL = 'http://api.eliteprospects.com:80/beta/teams'.freeze
  4.     LIMIT = 1000.freeze
  5.     FIELDS = %w(name country.name locality.name latestTeamStats.league.name).freeze
  6.  
  7.     class << self
  8.  
  9.       def fetch
  10.         raw_attrs = get_raw_clubs_attributes
  11.         parse_clubs_attributes(raw_attrs)
  12.       end
  13.  
  14.       private
  15.  
  16.       def get_raw_clubs_attributes(filter = {})
  17.         attrs = []
  18.         (0..total_count).step(LIMIT).each do |offset|
  19.           attrs += get_attrs_part(offset, FIELDS, filter)
  20.         end
  21.         attrs
  22.       end
  23.  
  24.       def parse_clubs_attributes(raw_clubs_attrs)
  25.         clubs_attrs = []
  26.         raw_clubs_attrs.each do |raw_attrs|
  27.           address = [raw_attrs.fetch('country', nil)&.fetch('name', nil),
  28.                      raw_attrs.fetch('locality', nil)&.fetch('name', nil)].join(' ')
  29.           division = raw_attrs.fetch('latestTeamStats', nil)&.fetch('league')&.fetch('name')
  30.           club_attrs = { name: raw_attrs['name'],
  31.                           address: address,
  32.                           division: division
  33.                         }
  34.           clubs_attrs << club_attrs
  35.         end
  36.         clubs_attrs
  37.       end
  38.  
  39.       def total_count
  40.         path = URL + '?limit=0'
  41.         response = HTTParty.get(path)
  42.         JSON.parse(response.body)['metadata']['totalCount']
  43.       end
  44.  
  45.       def get_attrs_part(offset, fields, filter = {})
  46.         _fields = fields.join(',')
  47.         _filter = filter.map { |k, v| "#{k}=#{v}" }.join('&')
  48.         path = URL + "?limit=#{LIMIT}&offset=#{offset}&filter=(#{_filter})&fields=#{_fields}"
  49.         response = HTTParty.get(path)
  50.         JSON.parse(response.body)['data']
  51.       end
  52.     end
  53.   end
  54. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement