<commit_before>require "net/http"
require "uri"

class ShareAnalyticsUpdater
  def self.update_shares
    puts "Fetching data..."

    uri = 'http://run.shareprogress.org/api/v1/buttons/analytics'
    uri = URI.parse(uri)

    Share::Button.all.each do |button|
      response = Net::HTTP.post_form(uri, {key: ENV['SHARE_PROGRESS_API_KEY'], id: button.sp_id})
      parsed_body = JSON.parse(response.body).with_indifferent_access
      if parsed_body[:success]
        button.update!(analytics: response.body )
      else
        raise "ShareProgress button update failed with the following message from their API: #{parsed_body[:message]}."
      end
    end

    puts "Fetching has completed."
  end
end<commit_msg>Tidy up share analytics updater class<commit_after>require "net/http"
require "uri"

class ShareAnalyticsUpdater
  def self.update_shares
    new(nil).update_collection
  end

  def initialize(collection)
    #Collection can be passed explicitly in order to reuse this task to update only a section of buttons at a later time.
    @collection = collection || Share::Button.all
    @uri = URI.parse('http://run.shareprogress.org/api/v1/buttons/analytics')
    @sp_api_key = ENV['SHARE_PROGRESS_API_KEY']
  end

  def update_collection
    update_shares
  end

  private

  def update_shares
    @collection.each do |button|
      begin
        request_analytics_from_sp(button)
      rescue ::ShareProgressApiError
        puts $!.message
        next
      end
    end
  end

  def request_analytics_from_sp(button)
    response = Net::HTTP.post_form(@uri, {key: @sp_api_key, id: button.sp_id})
    raise_or_update(response, button)
  end

  def raise_or_update(response, button)
    parsed_body = JSON.parse(response.body).with_indifferent_access
    if parsed_body[:success]
      button.update!(analytics: response.body )
    else
      raise ::ShareProgressApiError, "ShareProgress button analytics update failed with the following message from their API: #{parsed_body[:message]}."
    end
  end
end
{'fraction_non_alphanumeric': 0.09302325581395349, 'fraction_numerical': 0.0009896091044037606, 'mean_word_length': 3.6059225512528474, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2873329', 'n_tokens_mistral': 622, 'n_tokens_neox': 622, 'n_words': 157}