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.



36
37
38
# File 'lib/syntropy/request_extensions.rb', line 36

def route
  @route
end

#route_paramsObject (readonly)

Returns the value of attribute route_params.



35
36
37
# File 'lib/syntropy/request_extensions.rb', line 35

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)


247
248
249
250
251
252
253
# File 'lib/syntropy/request_extensions.rb', line 247

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)


238
239
240
241
# File 'lib/syntropy/request_extensions.rb', line 238

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

#ctxObject

Returns the request context



55
56
57
# File 'lib/syntropy/request_extensions.rb', line 55

def ctx
  @ctx ||= {}
end

#get_form_dataHash

Reads the request body and returns form data.

Returns:

  • (Hash)

    form data



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

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



214
215
216
217
218
219
220
# File 'lib/syntropy/request_extensions.rb', line 214

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



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

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

#json_pretty_response(obj, **headers) ⇒ Object



230
231
232
233
234
235
236
# File 'lib/syntropy/request_extensions.rb', line 230

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



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

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



86
87
88
89
90
91
92
93
# File 'lib/syntropy/request_extensions.rb', line 86

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



101
102
103
104
105
106
107
108
109
110
# File 'lib/syntropy/request_extensions.rb', line 101

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



118
119
120
121
122
123
124
125
126
127
# File 'lib/syntropy/request_extensions.rb', line 118

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



48
49
50
51
52
# File 'lib/syntropy/request_extensions.rb', line 48

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:



158
159
160
161
162
163
164
165
166
167
168
# File 'lib/syntropy/request_extensions.rb', line 158

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



179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
# File 'lib/syntropy/request_extensions.rb', line 179

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



65
66
67
68
69
# File 'lib/syntropy/request_extensions.rb', line 65

def validate_http_method(*accepted)
  return method if accepted.include?(method)

  raise Syntropy::Error.method_not_allowed
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



143
144
145
# File 'lib/syntropy/request_extensions.rb', line 143

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