Module: Syntropy::RequestExtensions

Defined in:
lib/syntropy/request_extensions.rb

Overview

Extensions for the Qeweney::Request class

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#routeObject

Returns the value of attribute route.



10
11
12
# File 'lib/syntropy/request_extensions.rb', line 10

def route
  @route
end

#route_paramsObject (readonly)

Returns the value of attribute route_params.



9
10
11
# File 'lib/syntropy/request_extensions.rb', line 9

def route_params
  @route_params
end

Instance Method Details

#accept?(mime_type) ⇒ bool

Returns true if the accept header includes the given MIME type

Parameters:

  • mime_type (String)

    MIME type

Returns:

  • (bool)


221
222
223
224
225
226
227
# File 'lib/syntropy/request_extensions.rb', line 221

def accept?(mime_type)
  accept = headers['accept']
  return nil if !accept

  @accept_parts ||= parse_accept_parts(accept)
  @accept_parts.include?(mime_type)
end

#browser?Boolean

Returns:

  • (Boolean)


212
213
214
215
# File 'lib/syntropy/request_extensions.rb', line 212

def browser?
  user_agent = headers['user-agent']
  user_agent && user_agent =~ /^Mozilla\//
end

#ctxObject

Returns the request context



29
30
31
# File 'lib/syntropy/request_extensions.rb', line 29

def ctx
  @ctx ||= {}
end

#get_form_dataHash

Reads the request body and returns form data.

Returns:

  • (Hash)

    form data



177
178
179
180
181
182
183
184
185
186
# File 'lib/syntropy/request_extensions.rb', line 177

def get_form_data
  body = read
  if !body || body.empty?
    raise Syntropy::Error.new('Missing form data', Qeweney::Status::BAD_REQUEST)
  end

  Qeweney::Request.parse_form_data(body, headers)
rescue Qeweney::BadRequestError
  raise Syntropy::Error.new('Invalid form data', Qeweney::Status::BAD_REQUEST)
end

#html_response(html, **headers) ⇒ Object



188
189
190
191
192
193
194
# File 'lib/syntropy/request_extensions.rb', line 188

def html_response(html, **headers)
  respond(
    html,
    'Content-Type' => 'text/html; charset=utf-8',
    **headers
  )
end

#initialize(headers, adapter) ⇒ Object

Initializes request with additional fields



13
14
15
16
17
18
19
# File 'lib/syntropy/request_extensions.rb', line 13

def initialize(headers, adapter)
  @headers  = headers
  @adapter  = adapter
  @route = nil
  @route_params = {}
  @ctx = nil
end

#json_pretty_response(obj, **headers) ⇒ Object



204
205
206
207
208
209
210
# File 'lib/syntropy/request_extensions.rb', line 204

def json_pretty_response(obj, **headers)
  respond(
    JSON.pretty_generate(obj),
    'Content-Type' => 'application/json; charset=utf-8',
    **headers
  )
end

#json_response(obj, **headers) ⇒ Object



196
197
198
199
200
201
202
# File 'lib/syntropy/request_extensions.rb', line 196

def json_response(obj, **headers)
  respond(
    JSON.dump(obj),
    'Content-Type' => 'application/json; charset=utf-8',
    **headers
  )
end

#respond_by_http_method(map) ⇒ void

This method returns an undefined value.

Responds according to the given map. The given map defines the responses for each method. The value for each method is either an array containing the body and header values to use as response, or a proc returning such an array. For example:

req.respond_by_http_method(
  'head'  => [nil, headers],
  'get'   => -> { [IO.read(fn), headers] }
)

If the request’s method is not included in the given map, an exception is raised.

Parameters:

  • map (Hash)

    hash mapping HTTP methods to responses



60
61
62
63
64
65
66
67
# File 'lib/syntropy/request_extensions.rb', line 60

def respond_by_http_method(map)
  value = map[self.method]
  raise Syntropy::Error.method_not_allowed if !value

  value = value.() if value.is_a?(Proc)
  (body, headers) = value
  respond(body, headers)
end

#respond_on_get(body, headers = {}) ⇒ void

This method returns an undefined value.

Responds to GET requests with the given body and headers. Otherwise raises an exception.

Parameters:

  • body (String, nil)

    response body

  • headers (Hash) (defaults to: {})

    response headers



75
76
77
78
79
80
81
82
83
84
# File 'lib/syntropy/request_extensions.rb', line 75

def respond_on_get(body, headers = {})
  case self.method
  when 'head'
    respond(nil, headers)
  when 'get'
    respond(body, headers)
  else
    raise Syntropy::Error.method_not_allowed
  end
end

#respond_on_post(body, headers = {}) ⇒ void

This method returns an undefined value.

Responds to POST requests with the given body and headers. Otherwise raises an exception.

Parameters:

  • body (String, nil)

    response body

  • headers (Hash) (defaults to: {})

    response headers



92
93
94
95
96
97
98
99
100
101
# File 'lib/syntropy/request_extensions.rb', line 92

def respond_on_post(body, headers = {})
  case self.method
  when 'head'
    respond(nil, headers)
  when 'post'
    respond(body, headers)
  else
  raise Syntropy::Error.method_not_allowed
  end
end

#setup_mock_requestObject

Sets up mock request additional fields



22
23
24
25
26
# File 'lib/syntropy/request_extensions.rb', line 22

def setup_mock_request
  @route = nil
  @route_params = {}
  @ctx = nil
end

#validate(value, *clauses) ⇒ any

Validates and optionally converts a value against the given clauses. If no clauses are given, verifies the parameter value is not nil. A clause can be a class, such as String, Integer, etc, in which case the value is converted into the corresponding value. A clause can also be a range, for verifying the value is within the range. A clause can also be an array of two or more clauses, at least one of which should match the value. If the validation fails, an exception is raised.

Parameters:

  • value (any)

    value

Returns:

  • (any)

    validated value

Raises:



132
133
134
135
136
137
138
139
140
141
142
# File 'lib/syntropy/request_extensions.rb', line 132

def validate(value, *clauses)
  raise Syntropy::ValidationError, 'Validation error' if clauses.empty? && !value

  clauses.each do |c|
    valid = param_is_valid?(value, c)
    raise(Syntropy::ValidationError, 'Validation error') if !valid

    value = param_convert(value, c)
  end
  value
end

#validate_cache(cache_control: 'public', etag: nil, last_modified: nil) ⇒ void

This method returns an undefined value.

Validates request cache information. If the request cache information matches the given etag or last_modified values, responds with a 304 Not Modified status. Otherwise, yields to the given block for a normal response, and sets cache control headers according to the given arguments.

Parameters:

  • cache_control (String) (defaults to: 'public')

    value for Cache-Control header

  • etag (String, nil) (defaults to: nil)

    Etag header value

  • last_modified (String, nil) (defaults to: nil)

    Last-Modified header value



153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
# File 'lib/syntropy/request_extensions.rb', line 153

def validate_cache(cache_control: 'public', etag: nil, last_modified: nil)
  validated = false
  if (client_etag = headers['if-none-match'])
    validated = true if client_etag == etag
  end
  if (client_mtime = headers['if-modified-since'])
    validated = true if client_mtime == last_modified
  end
  if validated
    respond(nil, ':status' => Qeweney::Status::NOT_MODIFIED)
  else
    cache_headers = {
      'Cache-Control' => cache_control
    }
    cache_headers['Etag'] = etag if etag
    cache_headers['Last-Modified'] = last_modified if last_modified
    set_response_headers(cache_headers)
    yield
  end
end

#validate_http_method(*accepted) ⇒ String

Checks the request’s HTTP method against the given accepted values. If not included in the accepted values, raises an exception. Otherwise, returns the request’s HTTP method.

Parameters:

  • accepted (Array<String>)

    list of accepted HTTP methods

Returns:

  • (String)

    request’s HTTP method



39
40
41
42
43
# File 'lib/syntropy/request_extensions.rb', line 39

def validate_http_method(*accepted)
  raise Syntropy::Error.method_not_allowed if !accepted.include?(method)

  method
end

#validate_param(name, *clauses) ⇒ any

Validates and optionally converts request parameter value for the given parameter name against the given clauses. If no clauses are given, verifies the parameter value is not nil. A clause can be a class, such as String, Integer, etc, in which case the value is converted into the corresponding value. A clause can also be a range, for verifying the value is within the range. A clause can also be an array of two or more clauses, at least one of which should match the value. If the validation fails, an exception is raised. Example:

height = req.validate_param(:height, Integer, 1..100)

Parameters:

  • name (Symbol)

    parameter name

Returns:

  • (any)

    validated parameter value



117
118
119
# File 'lib/syntropy/request_extensions.rb', line 117

def validate_param(name, *clauses)
  validate(query[name], *clauses)
end