Class: ServiceContractWebmock::ContractMatcher

Inherits:
Object
  • Object
show all
Defined in:
lib/service_contract_webmock/contract_matcher.rb

Constant Summary collapse

INT =
Avro::Schema::PrimitiveSchema.new(:int)

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(endpoint, resources) ⇒ ContractMatcher

Returns a new instance of ContractMatcher.



8
9
10
11
# File 'lib/service_contract_webmock/contract_matcher.rb', line 8

def initialize(endpoint, resources)
  @endpoint = endpoint
  @resources = resources
end

Instance Attribute Details

#endpointObject (readonly)

Returns the value of attribute endpoint.



6
7
8
# File 'lib/service_contract_webmock/contract_matcher.rb', line 6

def endpoint
  @endpoint
end

#resourcesObject (readonly)

Returns the value of attribute resources.



6
7
8
# File 'lib/service_contract_webmock/contract_matcher.rb', line 6

def resources
  @resources
end

Instance Method Details

#extract_request(query) ⇒ Object



42
43
44
45
46
47
48
# File 'lib/service_contract_webmock/contract_matcher.rb', line 42

def extract_request(query)
  params = CGI.parse(query)
  fields.select {|field| field.name.in?(params.keys)}.each_with_object({}) do |field, acc|
    data = params[field.name][0].split(',').flat_map {|value| field.convert(value)}
    acc[field.name] = data
  end
end

#field_int?(name) ⇒ Boolean

Returns:

  • (Boolean)


38
39
40
# File 'lib/service_contract_webmock/contract_matcher.rb', line 38

def field_int?(name)
  fields.detect {|f| f.name == name}.try(:int?)
end

#fieldsObject



30
31
32
33
34
35
36
# File 'lib/service_contract_webmock/contract_matcher.rb', line 30

def fields
  @fields ||= endpoint.parameters.map do |param|
    param.type.definition.fields.map do |field|
      Field.new(field.name, field.type) unless ['page', 'per_page'].include?(field.name)
    end
  end.flatten.compact
end

#fields_and_paginationObject



22
23
24
# File 'lib/service_contract_webmock/contract_matcher.rb', line 22

def fields_and_pagination
  fields + pagination_fields
end

#found(query) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/service_contract_webmock/contract_matcher.rb', line 50

def found(query)
  search = extract_request(query)
  if search.empty?
    resources
  else
    resources.select do |resource|
      search.all? do |key, data|
        key = "id" if key == "ids"
        resource[key].in?(data)
      end
    end
  end
end

#pagination_fieldsObject



26
27
28
# File 'lib/service_contract_webmock/contract_matcher.rb', line 26

def pagination_fields
  [Field.new('page', INT), Field.new('per_page', INT)]
end

#to_regexObject



15
16
17
18
19
20
# File 'lib/service_contract_webmock/contract_matcher.rb', line 15

def to_regex
  params = fields_and_pagination.map do |field|
    "#{field.name}=#{field.value}&?"
  end.join("|")
  "(#{params})+"
end