Can you move some of the logic to the user model, rather than having it in the controller? That way, your code will be more DRY and better encapsulated.
views:
41answers:
3
+1
A:
Andrew Grimm
2010-06-07 23:04:04
+2
A:
As Andrew said, you need to have this logic in your user model. I will go a step further and make each condition a method to keep the code clean, understandable, reausable and follow Single Responsibility Principle. And also define a method in the user model that returns state, like so.
class User
def get_state(request)
return 'state1' if no_company_and_subdomain?(request)
return 'state2' if has_company_that_match_subdomain?(request)
return 'state3' if admin_has_company_that_match_subdomain?(request)
end
def no_company_and_subdomain?(request)
company.nil? && request.subdomains.empty?
end
def has_company_that_match_subdomain?(request)
return false if company.nil? || is_admin
company.downcase == request.subdomains.first.downcase
end
def admin_has_company_that_match_subdomain?(request)
return false if company.nil? || !is_admin
company.downcase == request.subdomains.first.downcase
end
end
and then your controller code will become like this
if !session[:user_id].nil?
@user = User.find(session[:user_id])
@user.get_state
end
Obviously, you can rename the methods more sensibly based on your requirements.
nas
2010-06-08 05:58:41
+1
A:
Check out replace type with polymorphism and replace type with strategy refactoring pattern (in your case latter one seems to fit better). It might simplify your code, especially if you have multiple similar conditionals in your code.
Refactoring Ruby is a good source of informations on that topic.
samuil
2010-06-11 19:11:08