Class: Smartling::Uri

Inherits:
Object
  • Object
show all
Defined in:
lib/smartling/uri.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(base, path = nil) ⇒ Uri

Returns a new instance of Uri


19
20
21
22
23
# File 'lib/smartling/uri.rb', line 19

def initialize(base, path = nil)
  @base = base
  @path = path
  @required = []
end

Instance Attribute Details

#baseObject

Returns the value of attribute base


17
18
19
# File 'lib/smartling/uri.rb', line 17

def base
  @base
end

#paramsObject

Returns the value of attribute params


17
18
19
# File 'lib/smartling/uri.rb', line 17

def params
  @params
end

#pathObject

Returns the value of attribute path


17
18
19
# File 'lib/smartling/uri.rb', line 17

def path
  @path
end

#requiredObject

Returns the value of attribute required


17
18
19
# File 'lib/smartling/uri.rb', line 17

def required
  @required
end

Instance Method Details

#format_query(params) ⇒ Object


49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/smartling/uri.rb', line 49

def format_query(params)
# TODO: UTF-8 encode keys and values
# URI.encode_www_form(params)
  params.map {|k,v|
    if v.respond_to?(:to_ary)
      v.to_ary.map {|w|
        k.to_s + '[]=' + format_value(w)
      }.join('&')
    else
      k.to_s + '=' + format_value(v)
    end
  }.join('&')
end

#format_time(t) ⇒ Object


68
69
70
# File 'lib/smartling/uri.rb', line 68

def format_time(t)
  t.utc.iso8601
end

#format_value(v) ⇒ Object


63
64
65
66
# File 'lib/smartling/uri.rb', line 63

def format_value(v)
  v.is_a?(Time) ? format_time(v) :
    CGI.escape(v.to_s).gsub('+', '%20')
end

#require(*args) ⇒ Object


25
26
27
28
# File 'lib/smartling/uri.rb', line 25

def require(*args)
  @required += args
  return self
end

#to_sObject


45
46
47
# File 'lib/smartling/uri.rb', line 45

def to_s
  to_uri.to_s
end

#to_uriObject

Raises:

  • (ArgumentError)

30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/smartling/uri.rb', line 30

def to_uri
  params = @params || {}
  required = @required || []
  params.delete_if {|k,v| v.nil? || v.to_s.size <= 0 }
  missing = required - params.keys
  raise ArgumentError, "Missing parameters: " + missing.inspect if missing.size > 0

  uri = URI.parse(@base)
  uri.merge!(@path) if @path
  if params.size > 0
    uri.query = format_query(params)
  end
  return uri
end