0

I have the following function in payment.rb

def self.create_customer_with_card arg
  customer_list = Curl.get("#{BaseURL}/customer") do |curl|
    curl.headers["Authorization"] = authorization_header
    curl.headers['Content-Type'] = 'application/json'
  end

  customer = Curl.get("#{BaseURL}/customer/660391") do |curl|
    curl.headers["Authorization"] = authorization_header
    curl.headers['Content-Type'] = 'application/json'
  end
  byebug
end

I placed the byebug at the end of function. when no matter either I check customer_list or customer it gives me result of customer. while if I try them individually results are okay. But keeping both in same function assigns the output of second function to both variables. I'm using gem 'curb', '~> 0.9.4' for curl. any idea?

tadman
  • 208,517
  • 23
  • 234
  • 262
Mani
  • 2,391
  • 5
  • 37
  • 81

1 Answers1

0

When you have a Ruby method of the form:

def x
  a = ...
  b = ...
end

The return value of this method is always the value assigned to the local variable b and any value assigned to local variable a is thrown away. Remember that local variables only exist within the scope of your block unless closures are involved. Outside of that scope any values they contain are thrown away unless otherwise retained.

If you want to return both values, just do this:

def self.create_customer_with_card arg
  [
    Curl.get("#{BaseURL}/customer") do |curl|
      curl.headers["Authorization"] = authorization_header
      curl.headers['Content-Type'] = 'application/json'
    end,
    Curl.get("#{BaseURL}/customer/660391") do |curl|
      curl.headers["Authorization"] = authorization_header
      curl.headers['Content-Type'] = 'application/json'
    end
  ]
end

Then you call it like this:

customer_list, customer = create_customer_with_card(arg)

Though arg is not used, so until it is you should remove it.

Once in this form it becomes fairly obvious a more minimal form is:

def self.create_customer_with_card
  [ "/customer", "/customer/660391" ].map do |path|
    Curl.get("#{BaseURL}#{path}") do |curl|
      curl.headers["Authorization"] = authorization_header
      curl.headers['Content-Type'] = 'application/json'
    end
  ]
end

Where that uses map to convert two paths to two results.

tadman
  • 208,517
  • 23
  • 234
  • 262