Sha256: 546c49bc3ad72b51102e8aa9e7a5387d8c9876ab86e8cd32f3e99aef7a0ab5b8

Contents?: true

Size: 1.91 KB

Versions: 6

Compression:

Stored size: 1.91 KB

Contents

# frozen_string_literal: true
require 'curb_core'
require 'curl/easy'
require 'curl/multi'
require 'uri'
require 'cgi'

# expose shortcut methods
module Curl

  def self.http(verb, url, post_body=nil, put_data=nil, &block)
    if Thread.current[:curb_curl_yielding]
      handle = Curl::Easy.new # we can't reuse this
    else
      handle = Thread.current[:curb_curl] ||= Curl::Easy.new
      handle.reset
    end
    handle.url = url
    handle.post_body = post_body if post_body
    handle.put_data = put_data if put_data
    if block_given?
      Thread.current[:curb_curl_yielding] = true
      yield handle
      Thread.current[:curb_curl_yielding] = false
    end
    handle.http(verb)
    handle
  end

  def self.get(url, params={}, &block)
    http :GET, urlalize(url, params), nil, nil, &block
  end

  def self.post(url, params={}, &block)
    http :POST, url, postalize(params), nil, &block
  end

  def self.put(url, params={}, &block)
    http :PUT, url, nil, postalize(params), &block
  end

  def self.delete(url, params={}, &block)
    http :DELETE, url, postalize(params), nil, &block
  end

  def self.patch(url, params={}, &block)
    http :PATCH, url, postalize(params), nil, &block
  end

  def self.head(url, params={}, &block)
    http :HEAD, urlalize(url, params), nil, nil, &block
  end

  def self.options(url, params={}, &block)
    http :OPTIONS, urlalize(url, params), nil, nil, &block
  end

  def self.urlalize(url, params={})
    uri = URI(url)
    # early return if we didn't specify any extra params
    return uri.to_s if (params || {}).empty?

    params_query = URI.encode_www_form(params || {})
    uri.query = [uri.query.to_s, params_query].reject(&:empty?).join('&')
    uri.to_s
  end

  def self.postalize(params={})
    params.respond_to?(:map) ? URI.encode_www_form(params) : (params.respond_to?(:to_s) ? params.to_s : params)
  end

  def self.reset
    Thread.current[:curb_curl] = Curl::Easy.new
  end

end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
curb-1.0.6 lib/curl.rb
curb-1.0.5 lib/curl.rb
curb-1.0.4 lib/curl.rb
curb-1.0.3 lib/curl.rb
curb-1.0.2 lib/curl.rb
curb-1.0.1 lib/curl.rb