File: utils.rb

package info (click to toggle)
ruby-journey 1.0.4-2.1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, sid, trixie
  • size: 288 kB
  • sloc: ruby: 2,830; javascript: 113; yacc: 42; makefile: 2
file content (57 lines) | stat: -rw-r--r-- 1,782 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
require 'uri'

module Journey
  class Router
    class Utils
      # Normalizes URI path.
      #
      # Strips off trailing slash and ensures there is a leading slash.
      #
      #   normalize_path("/foo")  # => "/foo"
      #   normalize_path("/foo/") # => "/foo"
      #   normalize_path("foo")   # => "/foo"
      #   normalize_path("")      # => "/"
      def self.normalize_path(path)
        path = "/#{path}"
        path.squeeze!('/')
        path.sub!(%r{/+\Z}, '')
        path = '/' if path == ''
        path
      end

      # URI path and fragment escaping
      # http://tools.ietf.org/html/rfc3986
      module UriEscape
        # Symbol captures can generate multiple path segments, so include /.
        reserved_segment  = '/'
        reserved_fragment = '/?'
        reserved_pchar    = ':@&=+$,;%'

        safe_pchar    = "#{URI::REGEXP::PATTERN::UNRESERVED}#{reserved_pchar}"
        safe_segment  = "#{safe_pchar}#{reserved_segment}"
        safe_fragment = "#{safe_pchar}#{reserved_fragment}"
        if RUBY_VERSION >= '1.9'
          UNSAFE_SEGMENT  = Regexp.new("[^#{safe_segment}]", false).freeze
          UNSAFE_FRAGMENT = Regexp.new("[^#{safe_fragment}]", false).freeze
        else
          UNSAFE_SEGMENT = Regexp.new("[^#{safe_segment}]", false, 'N').freeze
          UNSAFE_FRAGMENT = Regexp.new("[^#{safe_fragment}]", false, 'N').freeze
        end
      end

      Parser = URI.const_defined?(:Parser) ? URI::Parser.new : URI

      def self.escape_path(path)
        Parser.escape(path.to_s, UriEscape::UNSAFE_SEGMENT)
      end

      def self.escape_fragment(fragment)
        Parser.escape(fragment.to_s, UriEscape::UNSAFE_FRAGMENT)
      end

      def self.unescape_uri(uri)
        Parser.unescape(uri)
      end
    end
  end
end