Skip to content

Commit

Permalink
Tidy up FormsController
Browse files Browse the repository at this point in the history
  • Loading branch information
irisfaraway committed Dec 19, 2017
1 parent f7c6fed commit 2fb7537
Showing 1 changed file with 39 additions and 34 deletions.
73 changes: 39 additions & 34 deletions app/controllers/forms_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -25,41 +25,33 @@ def go_back

private

def set_transient_registration(reg_identifier)
@transient_registration = TransientRegistration.where(reg_identifier: reg_identifier).first ||
TransientRegistration.new(reg_identifier: reg_identifier)
end

# Expects a form class name (eg BusinessTypeForm), a snake_case name for the form (eg business_type_form),
# and the reg_identifier param
def set_up_form(form_class, form, reg_identifier)
set_transient_registration(reg_identifier)

unless @transient_registration.valid?
redirect_to page_path("errors/invalid")
return false
end

unless user_has_permission?
redirect_to page_path("errors/permission")
return false
end

unless form_matches_state?
redirect_to_correct_form
return false
end
return false unless transient_registration_is_valid? &&
user_has_permission? &&
state_is_correct?

# Set an instance variable for the form (eg. @business_type_form) using the provided class (eg. BusinessTypeForm)
instance_variable_set("@#{form}", form_class.new(@transient_registration))
end

def user_has_permission?
can? :update, @transient_registration
end

def set_transient_registration(reg_identifier)
@transient_registration = TransientRegistration.where(reg_identifier: reg_identifier).first ||
TransientRegistration.new(reg_identifier: reg_identifier)
end

def form_matches_state?
controller_name == "#{@transient_registration.workflow_state}s"
def submit_form(form, params)
respond_to do |format|
if form.submit(params)
@transient_registration.next!
format.html { redirect_to_correct_form }
else
format.html { render :new }
end
end
end

def redirect_to_correct_form
Expand All @@ -72,14 +64,27 @@ def form_path
send("new_#{@transient_registration.workflow_state}_path".to_sym, @transient_registration.reg_identifier)
end

def submit_form(form, params)
respond_to do |format|
if form.submit(params)
@transient_registration.next!
format.html { redirect_to_correct_form }
else
format.html { render :new }
end
end
# Guards

def transient_registration_is_valid?
return true if @transient_registration.valid?
redirect_to page_path("errors/invalid")
false
end

def user_has_permission?
return true if can? :update, @transient_registration
redirect_to page_path("errors/permission")
false
end

def state_is_correct?
return true if form_matches_state?
redirect_to_correct_form
false
end

def form_matches_state?
controller_name == "#{@transient_registration.workflow_state}s"
end
end

0 comments on commit 2fb7537

Please sign in to comment.