Satchel
Satchel

Reputation: 16724

removing code in ruby used in multiple class methods

I have the following, which is repeated four times:

def self.curl_delete(url, response_flag)
  url = "#{@baseUrl}#{url}"

  curl_response = Curl.delete(url) do |curl|
    curl.headers['Content-Type'] = 'text/plain'
    curl.headers['Client'] = 'Curb DELETE'
    curl.headers['Authorization'] = "Bearer #{@token}"
    curl.verbose = false
  end

  response = JSON.parse(curl_response.body_str)

  if response_flag == true
    BF.puts_and_file  "     *response flag set to true for DELETE*\n"
    BF.puts_and_file  "     url: #{url}\n"
    BF.puts_and_file  "     response: #{response}\n\n"
  end

  return response
end

I would like to turn that if statement into a method.

I tried def response_flag_true(flag) but didn't work...what's the right way to DRY up that code?

Upvotes: 0

Views: 36

Answers (1)

Cary Swoveland
Cary Swoveland

Reputation: 110675

Keep it simple:

def bf_puts_and_file(indent, *messages)
  messages.each { |s| BF.puts_and_file(' ' * indent + s) }
end

Used as follows:

bf_puts_and_file(5, "*response flag set to true for DELETE*\n",
                    "url: #{url}\n",
                    "response: #{response}\n\n") if response_flag

Upvotes: 1

Related Questions