Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create named routes for OmniAuth in Rails 3

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

or:

<%= link_to 'Sign in with Twitter', signin_path(:twitter) %>
<%= link_to 'Sign in with Facebook', signin_path(:facebook) %>

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.

like image 560
Daniel Perez Alvarez Avatar asked Dec 05 '10 23:12

Daniel Perez Alvarez


2 Answers

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 %>
like image 60
monocle Avatar answered Oct 21 '22 02:10

monocle


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

like image 38
Agent47DarkSoul Avatar answered Oct 21 '22 03:10

Agent47DarkSoul