0

I have a rails worker using redis/sidekiq where I send some data to an API (Active Campaign), so I normally use all the http configurations to send data. I want to have it nice and clean, so it's part of a refactor thing. My worker currently looks like this:

class UpdateLeadIdWorker
  include Sidekiq::Worker

  BASE_URL = Rails.application.credentials.dig(:active_campaign, :url)
  private_constant :BASE_URL
  API_KEY = Rails.application.credentials.dig(:active_campaign, :key)
  private_constant :API_KEY

  def perform(ac_id, current_user_id)
    lead = Lead.where(user_id: current_user_id).last
    url = URI("#{BASE_URL}/api/3/contacts/#{ac_id}") #<--- need this endpoint

    https = bindable_lead_client.assign(url)
    pr = post_request.assign(url)

    case lead.quote_type
    when 'renter'
      data = { contact: { fieldValues: [{ field: '5', value: lead.lead_id }] } }
    when 'home'
      data = { contact: { fieldValues: [{ field: '4', value: lead.lead_id }] } }
    when 'auto'
      data = { contact: { fieldValues: [{ field: '3', value: lead.lead_id }] } }
    else
      raise 'Invalid quote type'
    end

    pr.body = JSON.dump(data)
    response = JSON.parse(https.request(pr).read_body).symbolize_keys

    if response.code == '200'
      Rails.logger.info "Successfully updated contact #{ac_id} with lead id #{lead.lead_id}"
    else
      raise "Error creating contact: #{response.body}"
    end
  end

  def bindable_lead_client
    http = Net::HTTP.new(url.host, url.port)
    http.use_ssl = true
    http
  end

  def post_request
    post_request_ = Net::HTTP::Put.new(url)
    post_request_['Accept'] = 'application/json'
    post_request_['Content-Type'] = 'application/json'
    post_request_['api-token'] = API_KEY
    post_request_
  end
end

But whenever I run this I get:

2022-07-28T00:52:08.683Z pid=24178 tid=1s1u WARN: NameError: undefined local variable or method `url' for #<UpdateLeadIdWorker:0x00007fc713442be0 @jid="e2b9ddb6d5f4b8aecffa4d8b">
Did you mean? URI

I don't want everything stuck in one method. How could I achieve to make this cleaner? Thanks.

theKid
  • 522
  • 6
  • 19

1 Answers1

0

Pure ruby wise, The reason you get the error is because your method definition bindable_lead_client is missing the url argument. Hence undefined variable.

So def should look something like:

def bindable_lead_client (url)
    http = Net::HTTP.new(url.host, url.port)
    http.use_ssl = true
    http
end

and call:

bindable_lead_client(url)

As for how to make this code better, falls under question being too subjective under StackOverflow guidelines, which encourage you to ask more specific questions.

enter image description here

Shaunak
  • 17,377
  • 5
  • 53
  • 84