Method: ApplicationHelper#query_url

Defined in:
app/helpers/application_helper.rb

#query_url(base_url = nil, **params) ⇒ String

Utility to add additional query parameters to a URI.

Parameters:

  • base_url (String, nil) (defaults to: nil)

    A base URI to which to add parameters. If none is specified then the request URI for the current page will be used.

  • params (Hash{#to_s => #to_s})

    A hash of query parameters to add to the URI.

Returns:

  • (String)

    The stringified URI.



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'app/helpers/application_helper.rb', line 42

def query_url(base_url = nil, **params)
  uri = URI.parse(request.original_url)
  query = Rack::Utils.parse_nested_query uri.query

  unless base_url.nil?
    base_uri = URI.parse(base_url)
    base_query = Rack::Utils.parse_nested_query base_uri.query
    query = query.merge(base_query)
    uri.path = base_uri.path
  end

  query = query.merge(params.to_h { |k, v| [k.to_s, v.to_s] })
  uri.query = query.map { |k, v| "#{k}=#{v}" }.join('&')
  uri.to_s
end