我在ruby中有一個設置幾個實例變量的方法,有條件地,我想知道如何重構它來清理它並使其不那麼冗長。我的第一個嘗試是將不同的條件分解爲多個較小的幫助器方法,但我不確定這是否是正確的解決方法。任何建議都會有幫助。如何用Ruby中的多個布爾變量重構方法
def admin_view
if resource.present?
if resource.ed_level == 'group'
if current_user && (current_user.admin || resource.admins_byemail.include?(current_user.email))
@admin_full = true
@admin_edit = true
@admin_view = true
else
@admin_full = false
@admin_edit = false
@admin_view = false
end
else
if current_user && (current_user.admin || resource.admin_email_list('view').include?(current_user.email.downcase))
if current_user.admin || (resource.admin_email_list('full').include?(current_user.email.downcase) && resource.ed_level != 'group')
@admin_full = true
@admin_edit = true
@admin_view = true
elsif resource.admin_email_list('edit').include?(current_user.email.downcase) && resource.ed_level != 'group'
@admin_full = false
@admin_edit = true
@admin_view = true
elsif resource.admin_email_list('view').include?(current_user.email.downcase) && resource.ed_level != 'group'
@admin_full = false
@admin_edit = false
@admin_view = true
end
else
@admin_full = false
@admin_edit = false
@admin_view = false
end
end
else
redirect_to school_missing_path
end
end
根據下面的答案,我更新了我的代碼,如下所示。
def admin_view
if resource.present?
if resource.ed_level == 'group'
if current_user && (current_user.admin || resource.admins_byemail.include?(current_user.email))
set_admin_permissions(full: true, edit: true, view: true)
else
set_admin_permissions(full: false, edit: false, view: false)
end
else
if current_user && (current_user.admin || resource.admin_email_list('view').include?(current_user.email.downcase))
if current_user.admin || (resource.admin_email_list('full').include?(current_user.email.downcase) && resource.ed_level != 'group')
set_admin_permissions(full: true, edit: true, view: true)
elsif resource.admin_email_list('edit').include?(current_user.email.downcase) && resource.ed_level != 'group'
set_admin_permissions(full: false, edit: true, view: true)
elsif resource.admin_email_list('view').include?(current_user.email.downcase) && resource.ed_level != 'group'
set_admin_permissions(full: false, edit: false, view: true)
end
else
set_admin_permissions(full: false, edit: false, view: false)
end
end
else
redirect_to school_missing_path
end
end
private
def set_admin_permissions(full:, edit:, view:)
@admin_full = full
@admin_edit = edit
@admin_view = view
end
我認爲這個問題最好在[Code Review](http://codereview.stackexchange.com/)上收到。 –
謝謝...不知道代碼審查。 –