Module: Dagger::Utils

Defined in:
lib/dagger.rb

Class Method Summary collapse

Class Method Details

.append_key(root_key, key) ⇒ Object



75
76
77
# File 'lib/dagger.rb', line 75

def self.append_key(root_key, key)
  root_key.nil? ? key : "#{root_key}[#{key.to_s}]"
end

.encode_body(obj, opts = {}) ⇒ Object



50
51
52
53
54
55
56
57
58
59
# File 'lib/dagger.rb', line 50

def self.encode_body(obj, opts = {})
  return if obj.nil? || obj.empty?
  if obj.is_a?(String)
    obj
  elsif opts[:json]
    Oj.dump(obj, mode: :compat) # compat ensures symbols are converted to strings
  else
    to_query_string(obj)
  end
end

.parse_uri(uri) ⇒ Object

Raises:

  • (ArgumentError)


34
35
36
37
38
39
40
41
# File 'lib/dagger.rb', line 34

def self.parse_uri(uri)
  raise ArgumentError.new("Empty URI") if uri.to_s.strip == ''
  uri = 'http://' + uri unless uri.to_s['http']
  uri = URI.parse(uri)
  raise ArgumentError.new("Invalid URI: #{uri}") unless uri.is_a?(URI::HTTP)
  uri.path = '/' if uri.path == ''
  uri
end

.resolve_uri(uri, host = nil, query = nil) ⇒ Object



43
44
45
46
47
48
# File 'lib/dagger.rb', line 43

def self.resolve_uri(uri, host = nil, query = nil)
  uri = host + uri if uri.to_s[0] == '/' && host
  uri = parse_uri(uri.to_s)
  uri.path.sub!(/\?.*|$/, '?' + to_query_string(query)) if query and query.any?
  uri
end

.to_query_string(obj, key = nil) ⇒ Object



61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/dagger.rb', line 61

def self.to_query_string(obj, key = nil)
  if key.nil? && obj.is_a?(String) # && obj['=']
    return obj
  end

  case obj
  when Hash  then obj.map { |k, v| to_query_string(v, append_key(key, k)) }.join('&')
  when Array then obj.map { |v| to_query_string(v, "#{key}[]") }.join('&')
  when nil   then ''
  else
    "#{key}=#{ERB::Util.url_encode(obj.to_s)}"
  end
end