Class: RageController::API
- Inherits:
-
Object
- Object
- RageController::API
- Defined in:
- lib/rage/controller/api.rb
Class Method Summary collapse
-
.after_action(action_name = nil, **opts, &block) ⇒ Object
Register a new
after_action
hook. -
.before_action(action_name = nil, **opts, &block) ⇒ Object
Register a new
before_action
hook. -
.rescue_from(*klasses, with: nil, &block) ⇒ Object
Register a global exception handler.
-
.skip_before_action(action_name, only: nil, except: nil) ⇒ Object
Prevent a
before_action
hook from running. -
.wrap_parameters(key, include: [], exclude: []) ⇒ Object
Wraps the parameters hash into a nested hash.
Instance Method Summary collapse
-
#append_info_to_payload(payload) ⇒ Object
Define this method to add more information to request logs.
-
#authenticate_or_request_with_http_token {|token| ... } ⇒ Object
Authenticate using an HTTP Bearer token, or otherwise render an HTTP header requesting the client to send a Bearer token.
-
#authenticate_with_http_token {|token| ... } ⇒ Object
Authenticate using an HTTP Bearer token.
-
#cookies ⇒ Rage::Cookies
Get the cookie object.
-
#head(status) ⇒ Object
Send a response with no body.
-
#headers ⇒ Hash
Set response headers.
-
#params ⇒ Hash{Symbol=>String,Array,Hash,Numeric,NilClass,TrueClass,FalseClass}
Get the request data.
-
#render(json: nil, plain: nil, status: nil) ⇒ Object
Send a response to the client.
-
#request ⇒ Rage::Request
Get the request object.
-
#request_http_token_authentication ⇒ Object
Render an HTTP header requesting the client to send a Bearer token for authentication.
-
#reset_session ⇒ Object
Reset the entire session.
-
#response ⇒ Rage::Response
Get the response object.
-
#session ⇒ Rage::Session
Get the session object.
-
#stale?(etag: nil, last_modified: nil) ⇒ Boolean
Checks if the request is stale to decide if the action has to be rendered or the cached version is still valid.
Class Method Details
.after_action(action_name = nil, **opts, &block) ⇒ Object
Register a new after_action
hook. Calls with the same action_name
will overwrite the previous ones.
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 |
# File 'lib/rage/controller/api.rb', line 252 def after_action(action_name = nil, **opts, &block) action = prepare_action_params(action_name, **opts, &block) if @__after_actions && @__after_actions.frozen? @__after_actions = @__after_actions.dup end if @__after_actions.nil? @__after_actions = [action] elsif (i = @__after_actions.find_index { |a| a[:name] == action_name }) @__after_actions[i] = action else @__after_actions << action end end |
.before_action(action_name = nil, **opts, &block) ⇒ Object
The block form doesn’t receive an argument and is executed on the controller level as if it was a regular method.
Register a new before_action
hook. Calls with the same action_name
will overwrite the previous ones.
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 |
# File 'lib/rage/controller/api.rb', line 226 def before_action(action_name = nil, **opts, &block) action = prepare_action_params(action_name, **opts, &block) if @__before_actions && @__before_actions.frozen? @__before_actions = @__before_actions.dup end if @__before_actions.nil? @__before_actions = [action] elsif (i = @__before_actions.find_index { |a| a[:name] == action_name }) @__before_actions[i] = action else @__before_actions << action end end |
.rescue_from(*klasses, with: nil, &block) ⇒ Object
Register a global exception handler. Handlers are inherited and matched from bottom to top.
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 |
# File 'lib/rage/controller/api.rb', line 183 def rescue_from(*klasses, with: nil, &block) unless with if block_given? with = define_tmp_method(block) else raise ArgumentError, "No handler provided. Pass the `with` keyword argument or provide a block." end end if @__rescue_handlers.nil? @__rescue_handlers = [] elsif @__rescue_handlers.frozen? @__rescue_handlers = @__rescue_handlers.dup end @__rescue_handlers.unshift([klasses, with]) end |
.skip_before_action(action_name, only: nil, except: nil) ⇒ Object
Prevent a before_action
hook from running.
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 |
# File 'lib/rage/controller/api.rb', line 275 def skip_before_action(action_name, only: nil, except: nil) i = @__before_actions&.find_index { |a| a[:name] == action_name } raise ArgumentError, "The following action was specified to be skipped but couldn't be found: #{self}##{action_name}" unless i @__before_actions = @__before_actions.dup if @__before_actions.frozen? if only.nil? && except.nil? @__before_actions.delete_at(i) return end action = @__before_actions[i].dup if only action[:except] ? action[:except] |= Array(only) : action[:except] = Array(only) end if except action[:only] = Array(except) end @__before_actions[i] = action end |
.wrap_parameters(key, include: [], exclude: []) ⇒ Object
Wraps the parameters hash into a nested hash. This will allow clients to submit requests without having to specify any root elements. Params get wrapped only if the Content-Type
header is present and the params
hash doesn’t contain a param with the same name as the wrapper key.
307 308 309 310 |
# File 'lib/rage/controller/api.rb', line 307 def wrap_parameters(key, include: [], exclude: []) @__wrap_parameters_key = key @__wrap_parameters_options = { include:, exclude: } end |
Instance Method Details
#append_info_to_payload(payload) ⇒ Object
Define this method to add more information to request logs.
|
# File 'lib/rage/controller/api.rb', line 564
|
#authenticate_or_request_with_http_token {|token| ... } ⇒ Object
Authenticate using an HTTP Bearer token, or otherwise render an HTTP header requesting the client to send a Bearer token. For the authentication to be considered successful, the block should return a non-nil value.
500 501 502 |
# File 'lib/rage/controller/api.rb', line 500 def authenticate_or_request_with_http_token authenticate_with_http_token { |token| yield(token) } || request_http_token_authentication end |
#authenticate_with_http_token {|token| ... } ⇒ Object
Authenticate using an HTTP Bearer token. Returns the value of the block if a token is found. Returns nil
if no token is found.
465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 |
# File 'lib/rage/controller/api.rb', line 465 def authenticate_with_http_token auth_header = @__env["HTTP_AUTHORIZATION"] payload = if auth_header&.start_with?("Bearer") auth_header[7..] elsif auth_header&.start_with?("Token") auth_header[6..] end return unless payload token = if payload.start_with?("token=") payload[6..] else payload end token.delete_prefix!('"') token.delete_suffix!('"') yield token end |
#cookies ⇒ Rage::Cookies
Get the cookie object. See Rage::Cookies.
386 387 388 |
# File 'lib/rage/controller/api.rb', line 386 def @cookies ||= Rage::Cookies.new(@__env, @__headers) end |
#head(status) ⇒ Object
Send a response with no body.
439 440 441 442 443 444 445 446 447 |
# File 'lib/rage/controller/api.rb', line 439 def head(status) @__rendered = true @__status = if status.is_a?(Symbol) ::Rack::Utils::SYMBOL_TO_STATUS_CODE[status] else status end end |
#headers ⇒ Hash
Set response headers.
454 455 456 |
# File 'lib/rage/controller/api.rb', line 454 def headers @__headers end |
#params ⇒ Hash{Symbol=>String,Array,Hash,Numeric,NilClass,TrueClass,FalseClass}
Get the request data. The keys inside the hash are symbols, so params.keys
returns an array of Symbol
.
You can also load Strong Params to have Rage automatically wrap params
in an instance of ActionController::Parameters
.
At the same time, if you are not implementing complex filtering rules or working with nested structures, consider using native Hash#fetch
and Hash#slice
instead.
For multipart file uploads, the uploaded files are represented by an instance of Rage::UploadedFile.
527 528 529 |
# File 'lib/rage/controller/api.rb', line 527 def params @__params end |
#render(json: nil, plain: nil, status: nil) ⇒ Object
render
doesn’t terminate execution of the action, so if you want to exit an action after rendering, you need to do something like render(...) and return
.
Send a response to the client.
408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 |
# File 'lib/rage/controller/api.rb', line 408 def render(json: nil, plain: nil, status: nil) raise "Render was called multiple times in this action" if @__rendered @__rendered = true if json || plain @__body << if json json.is_a?(String) ? json : json.to_json else headers["content-type"] = "text/plain; charset=utf-8" plain.to_s end @__status = 200 end if status @__status = if status.is_a?(Symbol) ::Rack::Utils::SYMBOL_TO_STATUS_CODE[status] else status end end end |
#request ⇒ Rage::Request
Get the request object. See Rage::Request.
374 375 376 |
# File 'lib/rage/controller/api.rb', line 374 def request @request ||= Rage::Request.new(@__env) end |
#request_http_token_authentication ⇒ Object
Render an HTTP header requesting the client to send a Bearer token for authentication.
505 506 507 508 |
# File 'lib/rage/controller/api.rb', line 505 def request_http_token_authentication headers["Www-Authenticate"] = "Token" render plain: "HTTP Token: Access denied.", status: 401 end |
#reset_session ⇒ Object
Reset the entire session. See Rage::Session.
573 574 575 |
# File 'lib/rage/controller/api.rb', line 573 def reset_session session.clear end |
#response ⇒ Rage::Response
Get the response object. See Rage::Response.
380 381 382 |
# File 'lib/rage/controller/api.rb', line 380 def response @response ||= Rage::Response.new(@__headers, @__body) end |
#session ⇒ Rage::Session
Get the session object. See Rage::Session.
392 393 394 |
# File 'lib/rage/controller/api.rb', line 392 def session @session ||= Rage::Session.new() end |
#stale?(etag: nil, last_modified: nil) ⇒ Boolean
stale?
will set the response status to 304 if the request is fresh. This side effect will cause a double render error, if render
gets called after this method. Make sure to implement a proper conditional in your action to prevent this from happening:
if stale?(etag: "123")
render json: { hello: "world" }
end
Checks if the request is stale to decide if the action has to be rendered or the cached version is still valid. Use this method to implement conditional GET.
551 552 553 554 555 556 |
# File 'lib/rage/controller/api.rb', line 551 def stale?(etag: nil, last_modified: nil) still_fresh = request.fresh?(etag:, last_modified:) head :not_modified if still_fresh !still_fresh end |