File: strings.rb

package info (click to toggle)
ruby-fuzzyurl 0.8.0-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 168 kB
  • sloc: ruby: 517; makefile: 3
file content (56 lines) | stat: -rw-r--r-- 1,433 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
require 'fuzzyurl/fields'

class Fuzzyurl::Strings
  REGEX = %r{
    ^
    (?: (?<protocol> \* | [a-zA-Z][A-Za-z+.-]+) ://)?
    (?: (?<username> \* | [a-zA-Z0-9%_.!~*'();&=+$,-]+)
        (?: : (?<password> \* | [a-zA-Z0-9%_.!~*'();&=+$,-]*))?
        @
    )?
    (?<hostname> [a-zA-Z0-9\.\*\-]+?)?
    (?: : (?<port> \* | \d+))?
    (?<path> / [^\?\#]*)?                 ## captures leading /
    (?: \? (?<query> [^\#]*) )?
    (?: \# (?<fragment> .*) )?
    $
  }x

  class << self

    def from_string(str, opts={})
      return nil unless str.kind_of?(String)

      default = opts[:default]
      if m = REGEX.match(str)
        fu = Fuzzyurl.new
        Fuzzyurl::FIELDS.each do |f|
          fu.send("#{f}=", m[f] || default)
        end
        fu
      else
        raise ArgumentError, "Couldn't parse url string: #{str}"
      end
    end

    def to_string(fuzzyurl)
      if !fuzzyurl.kind_of?(Fuzzyurl)
        raise ArgumentError, "`fuzzyurl` must be a Fuzzyurl"
      end

      fu = fuzzyurl
      str = ""
      str << "#{fu.protocol}://" if fu.protocol
      str << "#{fu.username}" if fu.username
      str << ":#{fu.password}" if fu.password
      str << "@" if fu.username
      str << "#{fu.hostname}" if fu.hostname
      str << ":#{fu.port}" if fu.port
      str << "#{fu.path}" if fu.path
      str << "?#{fu.query}" if fu.query
      str << "##{fu.fragment}" if fu.fragment
      str
    end

  end
end