Sha256: e0d7360980cc99f0efcf0d8dc36b714050df3a6eb259b245713eb688af281693

Contents?: true

Size: 1.18 KB

Versions: 4

Compression:

Stored size: 1.18 KB

Contents

# frozen_string_literal: true

require "openssl"
require "net/http"
require "json"

module Spout
  module Helpers
    # Generates JSON web requests for POST and PATCH.
    class SendJson
      class << self
        def post(*args)
          new(*args).post
        end

        def patch(url, *args)
          new(url, *args).patch
        end
      end

      def initialize(url, args = {})
        @params = args
        @url = URI.parse(url)

        @http = Net::HTTP.new(@url.host, @url.port)
        if @url.scheme == "https"
          @http.use_ssl = true
          @http.verify_mode = OpenSSL::SSL::VERIFY_NONE
        end
      rescue
        @error = "Invalid URL: #{url.inspect}"
        puts @error.red
      end

      def post
        return unless @error.nil?

        header = { "Content-Type" => "application/json", "Accept" => "application/json" }
        response = @http.start do |http|
          http.post(@url.path, @params.to_json, header)
        end
        [JSON.parse(response.body), response]
      rescue => e
        puts "POST ERROR".red
        puts e.to_s.white
        nil
      end

      def patch
        @params["_method"] = "patch"
        post
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
spout-1.0.0 lib/spout/helpers/send_json.rb
spout-1.0.0.beta3 lib/spout/helpers/send_json.rb
spout-1.0.0.beta2 lib/spout/helpers/send_json.rb
spout-1.0.0.beta1 lib/spout/helpers/send_json.rb