Skip to content

Instantly share code, notes, and snippets.

@solnic
Created July 26, 2012 10:22
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save solnic/3181379 to your computer and use it in GitHub Desktop.
Save solnic/3181379 to your computer and use it in GitHub Desktop.
Determine current route name in Rails
def route_name
Rails.application.routes.recognize(request) { |route, _| route.name }.flatten.last.name.to_sym
end
@Hakon
Copy link

Hakon commented Jul 26, 2012

Rails.application.routes.router.recognize(request) do |route, matches, param|
  route.name
end

@solnic
Copy link
Author

solnic commented Jul 26, 2012

@Hakon thanks man. I updated the gist :)

@Hakon
Copy link

Hakon commented Jul 26, 2012

Or you could just do an explicit return from inside the block

  def route_name
    Rails.application.routes.router.recognize(request) do |route, _|
      return route.name.to_sym
    end
  end

@LTe
Copy link

LTe commented Jul 26, 2012

In ruby you do not need use return. Last line is return line ;)

@Hakon
Copy link

Hakon commented Jul 26, 2012

explicit return is needed because

Rails.application.routes.router.recognize(request)

returns a set of nested arrays and not the value of the block. It is also the last executed line in the route_name method.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment