Class: BrickFTP::APIComponent

Inherits:
Object
  • Object
show all
Defined in:
lib/brick_ftp/api_component.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path_template, query_keys = []) ⇒ APIComponent

Returns a new instance of APIComponent.



5
6
7
8
# File 'lib/brick_ftp/api_component.rb', line 5

def initialize(path_template, query_keys = [])
  @path_template = path_template.respond_to?(:call) ? path_template : ->(_) { path_template }
  @query_keys = query_keys.map(&:to_sym)
end

Instance Attribute Details

#path_template ⇒ Object (readonly)

Returns the value of attribute path_template.



3
4
5
# File 'lib/brick_ftp/api_component.rb', line 3

def path_template
  @path_template
end

#query_keys ⇒ Object (readonly)

Returns the value of attribute query_keys.



3
4
5
# File 'lib/brick_ftp/api_component.rb', line 3

def query_keys
  @query_keys
end

Instance Method Details

#build_path_params_from(params = {}) ⇒ Object



23
24
25
26
27
28
29
# File 'lib/brick_ftp/api_component.rb', line 23

def build_path_params_from(params = {})
  params = normalize_params(params)

  path_variables(params).each_with_object({}) do |key, res|
    res[key] = params[key]
  end
end

#build_query_params_from(params = {}) ⇒ Object



31
32
33
34
35
36
37
38
# File 'lib/brick_ftp/api_component.rb', line 31

def build_query_params_from(params = {})
  params = normalize_params(params)

  query_keys.each_with_object({}) do |name, res|
    next unless params.key?(name)
    res[name] = params[name]
  end
end

#build_query_string_from(params = {}) ⇒ Object



40
41
42
43
44
45
46
47
# File 'lib/brick_ftp/api_component.rb', line 40

def build_query_string_from(params = {})
  params = normalize_params(params)

  pairs = build_query_params_from(params).each_with_object([]) do |(k, v), res|
    res << "#{CGI.escape(k.to_s)}=#{CGI.escape(v.to_s)}"
  end
  pairs.join('&')
end

#except_path_and_query(params = {}) ⇒ Object



49
50
51
52
53
54
# File 'lib/brick_ftp/api_component.rb', line 49

def except_path_and_query(params = {})
  params = normalize_params(params)

  exceptions = path_variables(params) + query_keys
  params.reject { |k, _| exceptions.include?(k) }
end

#path(params) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/brick_ftp/api_component.rb', line 10

def path(params)
  params = normalize_params(params)

  path_params = build_path_params_from(params)
  escaped_path_params = path_params.each_with_object({}) do |(k, v), res|
    res[k] = CGI.escape(v.to_s)
  end

  path = path_template.call(params) % escaped_path_params
  query = build_query_string_from(params)
  query.empty? ? path : "#{path}?#{query}"
end