Creating Named Routes for OmniAuth in Rails 3

After I looked at Ryan, the excellent Railcast Simple OmniAuth , I was able to implement authentication in my application.

Everything works fine, but in my opinion, 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 it:

 <%= 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 processes these routes ... In my routes.rb , I have stuff for callbacks and checkout:

 match '/signin/:provider/callback' => 'sessions#create' match '/signout' => 'sessions#destroy', :as => :signout 

Therefore, I do not know where I could create these named routes.

Any help would be appreciated. Thanks.

+8
ruby-on-rails routes omniauth
source share
3 answers

Note that in link_to, you simply provide a string for the route argument. That way, you can simply define the method in the 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 the 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 %> 
+12
source share

Add this to your routes.rb

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

Now you can use the oauth_path URL helper to generate URLs.

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

0
source share

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') %> 
-6
source share

Source: https://habr.com/ru/post/649852/


All Articles