lib/usaidwat/service.rb in usaidwat-1.4.5 vs lib/usaidwat/service.rb in usaidwat-1.5.0

- old
+ new

@@ -1,66 +1,50 @@ +require 'requests' + module USaidWat module Service - class MockComment - attr_reader :subreddit, :body, :id, :link_id, :created_utc, :link_title, :ups, :downs - - def initialize(dict) - data = dict['data'] - @subreddit = data['subreddit'] - @body = data['body'] - @id = data['id'] - @link_id = data['link_id'] - @created_utc = data['created_utc'] - @link_title = data['link_title'] - @ups = data['ups'] - @downs = data['downs'] + class RedditService + def user(username) + data = %w{about comments submitted}.reduce({}) { |memo, obj| memo.update(obj.to_sym => get_page(username, obj)) } + USaidWat::Thing::User.new(username, data[:about], data[:comments], data[:submitted]) end - end - class MockSubmission - attr_reader :subreddit, :title, :created_utc, :permalink, :url + private - def initialize(dict) - data = dict['data'] - @subreddit = data['subreddit'] - @title = data['title'] - @created_utc = data['created_utc'] - @permalink = data['permalink'] - @url = data['url'] + def get_page(username, page) + url = "https://www.reddit.com/user/#{username}/#{page}.json" + url += '?limit=100' if ['comments', 'submitted'].include?(page) + get(url) end - end - class MockUser - def initialize(username) - @username = username + def get(uri) + hdrs = {'User-Agent' => "usaidwat v#{USaidWat::VERSION}"} + Requests.request('GET', uri, :headers => hdrs).json + rescue Timeout::Error + :server_error + rescue Requests::Error => e + case e.response.code.to_i + when 404 then :no_such_user + when 500 then :server_error + else :nil + end end + end - def about - load_data("user_#{@username}.json")['data'] + class MockService + def user(username) + USaidWat::Thing::User.new(username, + load_data("user_#{username}.json"), + load_data("#{username}.json"), + load_data("submissions_#{username}.json")) end - def comments(n) - json = load_data("#{@username}.json") - json['data']['children'].map { |d| MockComment.new(d) } - end - - def posts - json = load_data("submissions_#{@username}.json") - json['data']['children'].map { |d| MockSubmission.new(d) } - end - private def load_data(data_file) path = File.join(File.dirname(__FILE__), "..", "..", "features", "fixtures", data_file) - raise USaidWat::Client::NoSuchUserError, @username unless File.exists?(path) + return :no_such_user unless File.exists?(path) JSON.parse(IO.read(path)) - end - end - - class MockService - def user(username) - MockUser.new(username) end end end end