I’m new in Ruby on Rails and don’t know much about Ruby and Ruby on Rails styles. I started with authorization with omniauth. I want to sign in only with external services accounts. Next step will be authorization with multiple accounts.
But now I have this a bit ugly code, that creates new or returns old user when I go to /auth/twitter, for example. Can you tell me how to make it more ruby?
user.rb
class User < ActiveRecord::Base
has_many :authentications
def self.from_omniauth(auth)
authentication = Authentication.find_by_provider_and_uid(auth["provider"], auth["uid"])
authentication.nil? ? create_with_omniauth(auth) : authentication.user
end
def self.create_with_omniauth(auth)
@user = User.new
@user.name = auth["info"]["name"]
@user.save
@user.authentications.create_with_omniauth(auth, @user.id)
@user
end
end
authentication.rb
class Authentication < ActiveRecord::Base
belongs_to :user
def self.create_with_omniauth(auth, user_id)
@authentication = Authentication.new
@authentication.user_id = user_id
@authentication.provider = auth[:provider]
@authentication.uid = auth[:uid]
@authentication.save
end
end
authentication_controller.rb
class AuthenticationsController < ApplicationController
def index
@authentications = Authentication.all
end
def create
user = User.from_omniauth(request.env['omniauth.auth'])
session[:user_id] = user.id
redirect_to root_url, notice: "signed in"
end
def destroy
@authentication = Authentication.find(params[:id])
@authentication.destroy
redirect_to authentications_url, :notice => "Successfully destroyed authentication."
end
end
One thing you can do to make it more rails-y is to assign the members of a new object at creation time using the symbols of those members:
You will want to use the create call so that Rails will write to the DB, This way you don’t have to call the save function after you set the members to the values you want.
Also, I know you are trying to roll your own auth library, but you might want to look into the auth libraries that are out there such as AuthLogic.