Addressable Ruby Library

repository·main·Indexed 23 days ago

https://github.com/sporkmonger/addressable

A flexible Ruby implementation for URI and IRI parsing and manipulation. It provides enhanced support for RFC 3986, RFC 3987, and RFC 6570 (URI Templates). Key features include Addressable::URI for advanced parsing, normalization, and encoding; Addressable::Template for expanding and extracting variables from URI templates; and Addressable::IDNA for converting internationalized domain names between Unicode and ASCII (Punycode) per RFC 3490.

Tokens
4.3K
Snippets
5
Records
42
Agent score
81%

What's inside Addressable

  1. Install Addressable

    main

    Install the core gem using RubyGems:

    gem install addressable

    To enable native Internationalized Domain Name (IDN) support, you must install libidn on your system and the idn-ruby gem:

    Debian/Ubuntu:

    sudo apt-get install libidn11-dev

    OS X:

    brew install libidn

    Gem:

    gem install idn-ruby
    gem install addressable
  2. Configure Addressable dependency constraints

    main

    Addressable follows Semantic Versioning. When adding it to a Ruby project (e.g., in a .gemspec), it is recommended to use pessimistic version constraints to ensure compatibility while allowing for minor updates.

    To allow any version in the 2.7.x range:

    spec.add_dependency 'addressable', '~> 2.7'

    To require a specific minimum bug-fix version within a minor range:

    spec.add_dependency 'addressable', '~> 2.3', '>= 2.3.7'
    spec.add_dependency 'addressable', '~> 2.7'
  3. Expand URI Templates with Addressable::Template

    main

    Use Addressable::Template to implement RFC 6570 URI templates.

    • expand(data): Replaces template variables with values from a hash. If a variable is mapped to a hash, it can expand into query parameters.
    • partial_expand(data): Returns a template object where some variables have been replaced, but others remain as patterns (useful for partial matching).
    require "addressable/template"
    
    # Full expansion
    template = Addressable::Template.new("http://example.com/{?query*}")
    template.expand({
      "query" => {
        'foo' => 'bar',
        'color' => 'red'
      }
    })
    #=> #<Addressable::URI:0xc9d95c URI:http://example.com/?foo=bar&color=red>
    
    # Partial expansion
    template = Addressable::Template.new("http://example.com/{?one,two,three}")
    template.partial_expand({"one" => "1", "three" => 3}).pattern
    #=> "http://example.com/?one=1{&two}&three=3"
  4. Extract variables from a URI using Addressable::Template

    main

    You can use an Addressable::Template to extract data from an existing Addressable::URI. The extract method matches the URI against the template pattern and returns a hash of the captured components.

    require "addressable/template"
    
    template = Addressable::Template.new(
      "http://{host}{/segments*}/{?one,two,bogus}{#fragment}"
    )
    uri = Addressable::URI.parse(
      "http://example.com/a/b/c/?one=1&two=2#foo"
    )
    template.extract(uri)
    #=>
    # {
    #   "host" => "example.com",
    #   "segments" => ["a", "b", "c"],
    #   "one" => "1",
    #   "two" => "2",
    #   "fragment" => "foo"
    # }
  5. Parse and manipulate URIs with Addressable::URI

    main

    Use Addressable::URI.parse to create URI objects. These objects allow you to access components like scheme, host, and path. Addressable also supports IRI (Internationalized Resource Identifier) parsing and normalization.

    To convert an IRI (containing non-ASCII characters) into a normalized ASCII URI, use the .normalize method.

    require "addressable/uri"
    
    uri = Addressable::URI.parse("http://example.com/path/to/resource/")
    uri.scheme
    #=> "http"
    uri.host
    #=> "example.com"
    uri.path
    #=> "/path/to/resource/"
    
    uri = Addressable::URI.parse("http://www.詹姆斯.com/")
    uri.normalize
    #=> #<Addressable::URI:0xc9a4c8 URI:http://www.xn--8ws00zhy3a.com/>
  6. Convert internationalized domain names to ASCII with `Addressable::IDNA.to_ascii`

    main
    Use Addressable::IDNA.to_ascii(input) to convert a Unicode internationalized domain name into an ASCII domain name (Punycode) as described in RFC 3490. The method handles Unicode normalization (NFKC) and downcasing automatically. If the input does not contain multibyte characters, it returns the input as-is.
  7. Extract variables from a URI using a template

    main

    Use Addressable::Template#match to extract data from an existing URI based on a template pattern. It returns an Addressable::Template::MatchData object if the URI matches the pattern, or nil otherwise.

    Alternatively, use Addressable::Template#extract to get just the resulting Hash mapping directly.

    Like expand, you can provide a processor to handle restore(name, value) (to reverse transformations like percent-encoding) and match(name) (to provide custom regex for variable matching).

  8. Parse a URI with Addressable::URI.parse

    main

    Use Addressable::URI.parse to create a new URI object from a string. This method is compliant with RFC 3986 and RFC 3987. It handles standard URI components like scheme, authority, path, query, and fragment.

    If the input is already an Addressable::URI object, it returns a duplicate. If the input is a Ruby standard library URI object, it converts it to a string before parsing.