Module: Bearcat::Client::ClientModule

Defined Under Namespace

Classes: BearcatRequest

Constant Summary collapse

ARG_REGEX =
/:(\w+)/

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#_registered_endpointsObject (readonly)

Returns the value of attribute _registered_endpoints.



5
6
7
# File 'lib/bearcat/client_module.rb', line 5

def _registered_endpoints
  @_registered_endpoints
end

Instance Method Details

#context_types(types, &blk) ⇒ Object



77
78
79
# File 'lib/bearcat/client_module.rb', line 77

def context_types(types, &blk)
  types.each(&blk)
end

#endpoint(method, identifier, url = "", defaults: {}, &blk) ⇒ Object



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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/bearcat/client_module.rb', line 15

def endpoint(method, identifier, url = "", defaults: {}, &blk)
  if @current_prefix && !url.start_with?('/')
    url = url[2..-1] if url.start_with?('./')
    url = @current_prefix + url
  end

  args = url.to_enum(:scan, ARG_REGEX).map { Regexp.last_match }
  arg_names = args.map{|m| m[1]}

  @_registered_endpoints ||= {}
  @_registered_endpoints[identifier] = { symbol: identifier, method: method, url: url }

  # TODO: Consider generating the method using class_eval and a template - this will improve runtime performance
  # signature_bits = []
  # logical_bits = []
  # args.each do |m|
  #   name = [1]
  # end

  # interpolated_url = url.gsub(ARG_REGEX) do |m|
  #   '#{' + m[1] + '}'
  # end

  # class_eval <<~RUBY
  #   def #{identifier}(*args, **kwargs)
  #     parameters = {

  #     }

  #     #{method}(#{interpolated_url})
  #   end
  # RUBY

  define_method(identifier) do |*args, **kwargs|
    url_arguments = {}
    parameters = { }.with_indifferent_access
    parameters.merge!(defaults)

    args.each_with_index do |v, i|
      if arg_names[i]
        url_arguments[arg_names[i]] = v
      elsif i == arg_names.count && v.is_a?(Hash)
        parameters.merge!(v)
      else
        raise ArgumentError, "Too many arguments passed to #{identifier}" unless arg_names[i]
      end
    end

    parameters.merge!(kwargs)

    preq = BearcatRequest.new(url, url_arguments, parameters)
    yield preq if block_given?

    arg_names.each do |an|
      preq.arguments[an] = preq.parameters.delete(an) unless preq.arguments.key?(an)
      raise ArgumentError, "Missing argument #{an}" unless preq.arguments.key?(an)
    end

    send(method, preq.interpoated_url, preq.parameters)
  end
end

#prefix(prefix) ⇒ Object



7
8
9
10
11
12
13
# File 'lib/bearcat/client_module.rb', line 7

def prefix(prefix)
  past_prefix = @current_prefix
  @current_prefix = (past_prefix || '') + prefix
  yield
ensure
  @current_prefix = past_prefix
end