Sha256: ad6df32afcb2f98caeaa259c3e293ce7b750902562be3ab369713aee6c0615b4

Contents?: true

Size: 1.1 KB

Versions: 1

Compression:

Stored size: 1.1 KB

Contents

# frozen_string_literal: true

require_relative "builder/version"
require "uri"

module URI
  module Builder
    class Error < StandardError; end

    class DSL
      attr_reader :uri

      def initialize(uri)
        @uri = uri.clone
      end

      [:host, :scheme, :query, :fragment, :port].each do |property|
        define_method property do |value|
          wrap property, value
        end
      end

      def query(value)
        value = case value
        when Hash
          URI.encode_www_form value
        else
          value
        end

        wrap :query, value
      end

      def path(*segments)
        # Make sure there's a leading / if a non leading / is given.
        wrap :path, ::File.join(*segments.compact.map(&:to_s).prepend("/"))
      end

      def to_s
        uri.to_s
      end

      private
        def wrap(property, value)
          @uri.send "#{property}=", value
          self
        end
    end
  end

  def build
    Builder::DSL.new self
  end

  def self.build(value)
    URI(value).build
  end

  def self.env(key, default = nil)
    build ENV.fetch key, default
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
uri-builder-0.1.2 lib/uri/builder.rb