Sha256: eeb0a1165767621632ecb73294f90e3c5b0550e2e1cc78864453e912d7080be7

Contents?: true

Size: 1.22 KB

Versions: 4

Compression:

Stored size: 1.22 KB

Contents

module URI
  def build(scheme: "http", domain:, path: "/", query: "", fragment: "")
    if !query.is_a?(String)
      query = query.to_query # handles non-string argument, a Hash, for example
    end

    query = query.present? ? "?#{query.gsub(/\A\?/, "")}" : ""
    fragment = fragment.present? ? "##{fragment.gsub(/\A\#/, "")}" : ""

    return "#{scheme}://#{domain}#{path}#{query}#{fragment}"
  end

  module_function :build

  # use this to merge new query parameters into well-formed URI strings, pass averride as true to replace the query portion with the new one entirely
  def merge(uri="", new_query="", replace=false)
    parsed_uri = URI(uri)
    raise ArgumentError.new(":uri argument is not a well-formed uri string!") if parsed_uri.host.blank?

    query = !new_query.is_a?(String) ? (new_query.try(:to_query).presence || new_query.to_s) : new_query.to_s

    base_uri_options = {scheme: parsed_uri.scheme, domain: parsed_uri.host, path: parsed_uri.path, query: query, fragment: parsed_uri.fragment}

    if !replace
      query = parsed_uri.query.to_s.to_query_hash.merge(query.to_s.to_query_hash).to_query
    end

    new_uri = URI.build(**base_uri_options.merge(query: query))

    return new_uri
  end

  module_function :merge
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
creative_rails_utilities-0.4.8 lib/creative_rails_utilities/uri.rb
creative_rails_utilities-0.4.7 lib/creative_rails_utilities/uri.rb
creative_rails_utilities-0.4.6 lib/creative_rails_utilities/uri.rb
creative_rails_utilities-0.4.5 lib/creative_rails_utilities/uri.rb