lib/gratitude/tips.rb in gratitude-0.0.12 vs lib/gratitude/tips.rb in gratitude-0.1.0

- old
+ new

@@ -1,36 +1,53 @@ +# encoding: utf-8 + module Gratitude class Client module Tips - def current_tips - faraday.get(tips_url).body + begin + response = faraday.get(tips_url) + rescue Faraday::Error::ParsingError + raise AuthenticationError + end + response.body end def current_tips_total current_tips.inject(0) { |total, tip| total + tip["amount"].to_f } end def update_tips(array_of_hashes_with_usernames_and_amounts) - faraday.post do |request| - payload_for(request, array_of_hashes_with_usernames_and_amounts) - end.body + post_tips_to_gittip(array_of_hashes_with_usernames_and_amounts) end def update_tips_and_prune(array_of_hashes_with_usernames_and_amounts) - faraday.post do |request| - payload_for(request, array_of_hashes_with_usernames_and_amounts) - request.params = { :also_prune => "true"} - end.body + post_tips_to_gittip( + array_of_hashes_with_usernames_and_amounts, prune: true + ) end - private + private def tips_url "/#{username}/tips.json" end + def post_tips_to_gittip(array_of_hashes, options = {}) + response = faraday_post_response(array_of_hashes, options) + return_response_body_or_raise_update_error(response) + end + + def faraday_post_response(array_of_hashes, options = {}) + faraday.post do |request| + payload_for(request, array_of_hashes) + request.params = { also_prune: "true" } if options[:prune] == true + end + rescue + raise AuthenticationError + end + def payload_for(request, array_of_hashes) request.url(tips_url) request.body = prepared_tips_array(array_of_hashes).to_json end @@ -48,8 +65,23 @@ "platform" => "gittip", "username" => "#{username}" } end + def return_response_body_or_raise_update_error(response) + if usernames_with_errors(response.body).size > 0 + raise TipUpdateError, usernames_with_errors(response.body) + else + response.body + end + end + + def usernames_with_errors(response_body) + response_body.each_with_object([]) do |user_tip_response, array| + if user_tip_response.key?("error") + array << user_tip_response["username"] + end + end + end end # Tips end # Client end # Gratitude