Class: LibWebSocket::URL

Inherits:
Object
  • Object
show all
Defined in:
lib/libwebsocket/url.rb

Overview

Construct or parse a WebSocket URL.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(hash = {}) ⇒ URL

Returns a new instance of URL.



9
10
11
12
13
14
15
# File 'lib/libwebsocket/url.rb', line 9

def initialize(hash = {})
  hash.each do |k,v|
    instance_variable_set("@#{k}",v)
  end

  @secure ||= false
end

Instance Attribute Details

#hostObject

Returns the value of attribute host.



7
8
9
# File 'lib/libwebsocket/url.rb', line 7

def host
  @host
end

#portObject

Returns the value of attribute port.



7
8
9
# File 'lib/libwebsocket/url.rb', line 7

def port
  @port
end

#resource_nameObject

Returns the value of attribute resource_name.



7
8
9
# File 'lib/libwebsocket/url.rb', line 7

def resource_name
  @resource_name
end

#secureObject

Returns the value of attribute secure.



7
8
9
# File 'lib/libwebsocket/url.rb', line 7

def secure
  @secure
end

Instance Method Details

#parse(string) ⇒ Object

Parse a WebSocket URL.

Examples:

Parse

url = LibWebSocket::URL.new
url.parse('wss://example.com:3000')
url.host   # => example.com
url.port   # => 3000
url.secure # => true


24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/libwebsocket/url.rb', line 24

def parse(string)
  return nil unless string.is_a?(String)

  uri = Addressable::URI.parse(string)

  scheme = uri.scheme
  return nil unless scheme

  self.secure = true if scheme.match(/ss\Z/m)

  host = uri.host
  host = '/' unless host && host != ''
  self.host = host
  self.port = uri.port.to_s if uri.port

  request_uri = uri.path
  request_uri = '/' unless request_uri && request_uri != ''
  request_uri += "?" + uri.query if uri.query
  self.resource_name = request_uri

  return self
end

#to_sObject

Construct a WebSocket URL.

Examples:

Construct

url = LibWebSocket::URL.new
url.host = 'example.com'
url.port = '3000'
url.secure = true
url.to_s # => 'wss://example.com:3000'


54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/libwebsocket/url.rb', line 54

def to_s
  string = ''

  string += 'ws'
  string += 's' if self.secure
  string += '://'
  string += self.host
  string += ':' + self.port.to_s if self.port
  string += self.resource_name || '/'

  return string
end