Class: ApiSampler::RequestMatcher

Inherits:
Object
  • Object
show all
Defined in:
lib/api_sampler/request_matcher.rb

Overview

Match requests according to the specified rule.

Examples:

Regexp rule

rule = %r{^/api/v1}
matcher = ApiSampler::RequestMatcher.new(rule)
request = Rack::Request.new(Rack::MockRequest.env_for('http://example.com/api/v1/kittens'))
matcher.matches?(request) #=> true

Callable rule

rule = ->(r) { r.request_method == 'PUT' }
matcher = ApiSampler::RequestMatcher.new(rule)
request = Rack::Request.new(Rack::MockRequest.env_for('http://example.com/api/v1/kittens',
                                                      method: 'PUT'))
matcher.matches?(request) #=> true

Instance Method Summary collapse

Constructor Details

#initialize(rule) ⇒ RequestMatcher

Returns a new instance of RequestMatcher

Raises:

  • (ArgumentError)

    if rule has invalid type.


27
28
29
# File 'lib/api_sampler/request_matcher.rb', line 27

def initialize(rule)
  @rule = validate_and_normalize_rule(rule)
end

Instance Method Details

#matches?(request) ⇒ Boolean

Return true if the request matches, false otherwise.


35
36
37
# File 'lib/api_sampler/request_matcher.rb', line 35

def matches?(request)
  !!@rule.call(request)     # rubocop:disable Style/DoubleNegation
end