在Rails 3中为OmniAuth创建命名路由 [英] Create named routes for OmniAuth in Rails 3
问题描述
观看了Ryan出色的Railcast 简单的OmniAuth 之后,我设法实现了身份验证在我的应用中.
After having watched Ryan's excellent Railcast Simple OmniAuth, I've managed to implement authentication in my app.
一切正常,但是在我看来,我的链接看起来像这样:
Everything is working fine, but in my view I have links that look like this:
<%= link_to 'Sign in with Twitter', '/signin/twitter' %>
<%= link_to 'Sign in with Facebook', '/signin/facebook' %>
我想知道是否有一种优雅的方法来创建命名路由以替换为:
I was wondering if there is an elegant way to create a named route to replace that with:
<%= link_to 'Sign in with Twitter', signin_twitter_path %>
<%= link_to 'Sign in with Facebook', signin_facebook_path %>
或:
<%= link_to 'Sign in with Twitter', signin_path(:twitter) %>
<%= link_to 'Sign in with Facebook', signin_path(:facebook) %>
OmniAuth已经处理了这些路由...在我的routes.rb
文件中,我只有用于回调和退出的内容:
OmniAuth already handles those routes... In my routes.rb
file I only have stuff for callbacks and signing out:
match '/signin/:provider/callback' => 'sessions#create'
match '/signout' => 'sessions#destroy', :as => :signout
所以我不知道在哪里可以创建那些命名的路由.
So I don't know where I could create those named routes.
任何帮助将不胜感激.谢谢.
Any help will be appreciated. Thanks.
推荐答案
请注意,在link_to中,您只是为route参数提供了一个字符串.因此,您只需在助手文件中定义一个方法即可.
Notice that in link_to, you're just providing a string for the route argument. So you can just define a method in a helpers file.
# application_helper.rb
module ApplicationHelper
def signin_path(provider)
"/auth/#{provider.to_s}"
end
end
# view file
<%= link_to 'Sign in with Twitter', signin_path(:twitter) %>
如果您想获取所有元数据
If you want to get all meta
# application_helper.rb
module ApplicationHelper
def method_missing(name, *args, &block)
if /^signin_with_(\S*)$/.match(name.to_s)
"/auth/#{$1}"
else
super
end
end
end
#view file
<%= link_to 'Sign in with Twitter', signin_with_twitter %>
这篇关于在Rails 3中为OmniAuth创建命名路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!