\$\begingroup\$
\$\endgroup\$
Here is a method I have in my ApplicationController
, but it's "ugly" and needs some cleanup.
def user_root_path
return root_url unless user_signed_in?
return admin_root_url if current_user.admin?
return contributor_dashboard_url if current_user.athlete_contributor? && !current_user.class.name.eql?("Athlete")
return school_admin_athletes_path if current_user.role?("School Admin")
case current_user.class.name
when "Athlete"
if current_user.username.present?
edit_vitals_athlete_profile_path
else
account_finalize_path
end
when "HighSchoolCoach"
school_admin_athletes_path
when "CollegeCoach"
if current_user.sports.blank? || current_user.college_id.blank?
account_finalize_path
else
search_index_path
end
else
root_url
end
end
Phrancis
20.5k6 gold badges69 silver badges155 bronze badges
asked Jan 28, 2014 at 19:51
1 Answer 1
\$\begingroup\$
\$\endgroup\$
0
I would solve this with a combination of inheritance and duck typing.
- Use a base method on a
User
classroot_path
to be your entry point. - Pull out that nasty "signed out" user concept to a
NullUser
object, it is safer than passing nils around or constantly callinguser_signed_in?
everywhere. - Delegate from the
root_path
method in the base class tospecific_root_path
in subclasses once you are past your "early exit" logic.
# application_controller.rb
class ApplicationController < ActionController::Base
before_filter :set_current_user
def user_root_path
@user.root_path
end
def set_current_user
@user = current_user
@user ||= NullUser.new
end
end
# user.rb
class User < ActiveRecord::Base
include Rails.application.routes.url_helpers
def admin?
# your admin logic
end
def root_path
return admin_root_url if self.admin?
return school_admin_athletes_path if self.role?("School Admin")
if self.athlete_contributor? &&
!self.class.name.eql?("Athlete")
return contributor_dashboard_url
end
specific_root_path
end
def specific_root_path
root_url
end
end
class NullUser
include Rails.application.routes.url_helpers
def root_path
root_url
end
end
# athlete.rb
class Athlete < User
def specific_root_path
if self.username.present?
edit_vitals_athlete_profile_path
else
account_finalize_path
end
end
end
# high_school_coach.rb
class HighSchoolCoach < User
def specific_root_path
school_admin_athletes_path
end
end
# college_coach.rb
class CollegeCoach < User
def specific_root_path
if self.sports.blank? || self.college_id.blank?
account_finalize_path
else
search_index_path
end
end
end
This logic should be equivalent to your original logic, if it isn't, it is pretty close.
lang-rb