class Webspicy::Web::Mocker

Attributes

config[R]
generator[R]

Public Class Methods

new(config) click to toggle source
# File lib/webspicy/web/mocker.rb, line 7
def initialize(config)
  @config = Configuration.dress(config)
  @generator = config.generator || Finitio::Generation.new
end

Public Instance Methods

call(env) click to toggle source
# File lib/webspicy/web/mocker.rb, line 13
def call(env)
  req = Rack::Request.new(env)
  path = req.path
  meth = req.request_method
  if meth == "OPTIONS" && has_service?(path)
    [204, {}, []]
  elsif service = find_service(meth, path)
    status = best_status_code(service)
    body = status == 204 ? "" : random_body(service, req)
    headers = generate_headers(service)
    [ status, headers, [ body ].compact ]
  else
    [404, {}, []]
  end
end

Private Instance Methods

best_content_type(service) click to toggle source
# File lib/webspicy/web/mocker.rb, line 67
def best_content_type(service)
  if ex = service.examples.first
    ex.expected_content_type
  else
    "application/json"
  end
end
best_status_code(service) click to toggle source
# File lib/webspicy/web/mocker.rb, line 59
def best_status_code(service)
  if ex = service.examples.first
    (ex.expected_status && ex.expected_status.to_i) || 200
  else
    200
  end
end
find_service(method, path) click to toggle source
# File lib/webspicy/web/mocker.rb, line 41
def find_service(method, path)
  config.each_scope do |scope|
    scope.each_specification do |specification|
      next unless url_matches?(specification, path)
      scope.each_service(specification) do |service|
        return service if service.method == method
      end
    end
  end
  nil
end
generate_headers(service) click to toggle source
# File lib/webspicy/web/mocker.rb, line 53
def generate_headers(service)
  {
    "Content-Type" => best_content_type(service)
  }.delete_if{|k,v| v.nil? }
end
has_service?(path) click to toggle source
# File lib/webspicy/web/mocker.rb, line 31
def has_service?(path)
  config.each_scope do |scope|
    scope.each_specification do |specification|
      next unless url_matches?(specification, path)
      return true
    end
  end
  return false
end
random_body(service, request) click to toggle source
# File lib/webspicy/web/mocker.rb, line 79
def random_body(service, request)
  world = OpenStruct.new({
    service: service,
    request: request
  })
  data = generator.call(service.output_schema.main, world)
  JSON.pretty_generate(data) if data
end
url_matches?(specification, path) click to toggle source
# File lib/webspicy/web/mocker.rb, line 75
def url_matches?(specification, path)
  specification.url_pattern.match(path)
end