Create named routes for OmniAuth in Rails 3

北慕城南 提交于 2019-12-03 03:39:51

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 %>

Add this to your routes.rb

get "/auth/:provider", to: lambda{ |env| [404, {}, ["Not Found"]] }, as: :oauth

Now you can use oauth_path url helper to generate urls.

Eg. oauth_path(:facebook) # => /auth/facebook

With Rails 3 you can do :

# routes.rb
match '/signin/:provider/callback' => 'sessions#create', :as => :signing

#view.erb
<%= link_to 'twitter', signing_path(:provider => 'twitter') %>
<%= link_to 'facebook', signing_path(:provider => 'facebook') %>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!