Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - Extract HTTP Verb From Named Route

Is there a way in Rails to extract the HTTP verb(s) associated with a route? For example, given a route like this:

match 'users', to: 'users#show', via: [:get, :post]

Can I achieve something like this?

users_path.respond_to?(:get) (obviously #respond_to is not the right method)

The closest I've managed to come is by doing the following, but it doesn't really seem satisfactory.

Rails.application.routes.routes.named_routes["users"].constraints[:request_method] # => /^GET$/

For context, I have an action that sets a cookie and then does a redirect_to :back, but this action is available globally across the entire site (it's in the footer). So, if a user happens to be in a flow, and one of those routes only accepts POSTs, the redirect fails because the request issued is a GET.

like image 944
Marlorn Avatar asked Dec 31 '13 05:12

Marlorn


2 Answers

The request object is available to your controller. The following methods are available to determine the type of HTTP request:

if request.get?
  # request is a GET request
if request.post?
  # request is a POST request

There are similar methods for other HTTP request verbs, including PUT and DELETE.

UPDATE:

Per the update to the question, the following code can be implemented within your controller to yield the constrained verbs on any named route as a pipe-delimited string:

Rails.application.routes.named_routes["users"].verb
#=> "GET|POST" 

Accordingly, you can split the string to retrieve an array of each of the HTTP methods specified in the route's constraints:

methods_string = Rails.application.routes.named_routes["users"].verb
#=> "GET|POST"

methods_array = methods_string.split('|')
#=> ["GET", "POST"]

methods_array[0]
#=> "GET"
methods_array[1]
#=> "POST"
like image 162
zeantsoi Avatar answered Nov 14 '22 07:11

zeantsoi


for someone looking with it in future you can use

env["REQUEST_METHOD"]

to get HTTP verb of specific action

like image 20
Jomar Gregorio Avatar answered Nov 14 '22 06:11

Jomar Gregorio