Project

local_uri

0.0
No commit activity in last 3 years
No release in over 3 years
Useful and slight extension to Ruby's URI (Uniform Resource Identifiers) core module.
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Dependencies

Development

>= 0
>= 0
>= 0
~> 0.58.2
~> 1.26.0

Runtime

 Project Readme

Quick start guide

  gem install local_uri

or add it to your Gemfile:

  gem 'local_uri'

Replace ruby core URI with LocalUri::URI.

In plain ruby:

define_method(:URI, ->(string) { LocalUri::URI.new(string) })

In rails:

# config/initalizers/uri.rb

define_method(:URI, ->(string) { LocalUri::URI.new(string) })

If you already have code in place that uses ruby core URI you can skip the replacement and just use LocalUri::URI directly:

LocalUri::URI.new('https://local.ch')

Working with URIs

LocalUri::URI has the following capabilities:

Queries

Merge hashes into url queries

merge(hash) - returns a copy of the base LocalUri::URI with given hash being merged into the query params:

uri = URI('https://yellow.local.ch/d/abc')
uri.to_s # https://yellow.local.ch/d/abc

uri.query.merge(tracking_id: 123).to_s # https://yellow.local.ch/d/abc?tracking_id=123

If you place those urls directly in the view or api response, an explicit to_s is not necessary:

%a{href: URI('https://yellow.local.ch/d/abc').query.merge(tracking_id: 123)} # <a href="https://yellow.local.ch/d/abc?tracking_id=123"/>

merge!(hash) - the same as merge but changes the original URI.

merge(hash) and merge!(hash) also support nested query:

uri = URI('https://booking-widget.local.ch/entries/abc/bookings/new')
uri.query.merge(booking: { people: 2 }).to_s # https://booking-widget.local.ch/entries/abc/bookings/new?booking[people]=2

Access data in queries

uri = URI('https://local.ch?id=1&place[name]=casa')
uri.query[:id] # '1'
uri.query.dig(:place, :name) # 'casa'

Remove parts of a query

uri = URI('https://local.ch?one=1&two=2&three=3')
uri.query.except(:two, :three).to_s # https://local.ch?one=1

except(keys) - Returns a uri which query includes everything except given keys.

except!(keys) - Removes the given keys from the query of the original uri and returns the uri itself.