class ApiSpec::Parameters

Attributes

query[R]

Public Class Methods

new(method, path, table = nil) click to toggle source
# File lib/api_spec/parameters.rb, line 5
def initialize(method, path, table = nil)
  @method = method
  @path = path

  @path_params = {}
  @query = {}
  @form = {}
  @json = {}
  @cookie = {}
  @header = {}

  load_table(table) if table
end

Public Instance Methods

body() click to toggle source
# File lib/api_spec/parameters.rb, line 36
def body
  if @json.any?
    @json.to_json
  elsif @form.any?
    @form
  else
    ""
  end
end
content_type_headers() click to toggle source
# File lib/api_spec/parameters.rb, line 60
def content_type_headers
  if @json.any?
    # {"Content-Type" => "application/json"}
    {content_type: :json, "CONTENT_TYPE" => "application/json"}
  else
    {}
  end
end
headers() click to toggle source
# File lib/api_spec/parameters.rb, line 46
def headers
  @header.merge(cookie_header).merge(content_type_headers)
end
method_missing(name) click to toggle source
# File lib/api_spec/parameters.rb, line 32
def method_missing(name)
  State.get(name)
end
url() click to toggle source
# File lib/api_spec/parameters.rb, line 19
def url
  interpolated_path = @path.scan(/\{(.*?)\}/).reduce(@path) do |path, match|
    key = match.first
    value = @path_params[key]

    raise StandardError.new("Missing #{key}") unless value

    path.gsub /\{#{key}\}/, URI.encode(value)
  end

  "http://localhost:#{$port}#{interpolated_path}"
end

Private Instance Methods

json_value(value_string) click to toggle source
# File lib/api_spec/parameters.rb, line 120
def json_value(value_string)
  JSON.parse("{\"value\":#{value_string}}")["value"]
rescue JSON::ParserError
  value_string
end
load_table(table) click to toggle source
# File lib/api_spec/parameters.rb, line 71
def load_table(table)
  table.hashes.each do |hash|
    matches = hash[:value].match(/\{(.*)\}/)
    key = hash["parameter name"]

    value = if matches
      method = matches[1]
      hash[:value].gsub(/\{#{method}\}/, send(method).to_s)
    else
      hash[:value]
    end

    set_param(hash["parameter type"], key, value)
  end
end
set_param(type, key, value) click to toggle source
# File lib/api_spec/parameters.rb, line 87
def set_param(type, key, value)
  case type
  when "path"
    @path_params[key] = value
  when "query"
    @query[key] = value
  when "json"
    parts = key.split("/")

    hash = parts.reverse.reduce(nil) do |acc, part|
      if part.match(/\d+/)
        [acc || json_value(value)]
      else
        if acc
          {part => acc}
        else
          {part => json_value(value)}
        end
      end
    end

    @json.merge!(hash)
  when "form"
    @form[key] = value
  when "cookie"
    @cookie[key] = value
  when "header"
    @header[key] = value
  else
    fail "Unrecognized parameter type: #{type}"
  end
end