Created
October 9, 2013 16:17
-
-
Save jteneycke/6903875 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ModelWizard | |
attr_reader :object | |
def initialize(object_or_class, session, params = nil, param_key = nil) | |
@object_or_class = object_or_class | |
@session = session | |
@params = params | |
@param_key = param_key || ActiveModel::Naming.param_key(object_or_class) | |
@session_params = "#{@param_key}_params".to_sym | |
end | |
def start | |
@session[@session_params] = {} | |
set_object | |
@object.current_step = 0 | |
self | |
end | |
def process | |
@session[@session_params].deep_merge!(@params[@param_key]) if @params[@param_key] | |
set_object | |
@object.assign_attributes(@session[@session_params]) unless class? | |
self | |
end | |
def save | |
saved = false | |
if @params[:back_button] | |
@object.step_back | |
elsif @object.current_step_valid? | |
binding.pry | |
if @object.last_step? | |
if @object.all_steps_valid? | |
saved = @object.save | |
@session[@session_param] = nil | |
end | |
else | |
@object.step_forward | |
end | |
end | |
saved | |
end | |
private | |
def set_object | |
@object = class? ? @object_or_class.new(@session[@session_params]): @object_or_class | |
end | |
def class? | |
@object_or_class.is_a?(Class) | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module MultiStepModel | |
attr_accessor :current_step | |
def current_step | |
@current_step.to_i | |
end | |
def current_step_valid? | |
valid? | |
end | |
def all_steps_valid? | |
(0...self.class.total_steps).all? do |step| | |
@current_step = step | |
current_step_valid? | |
end | |
end | |
def step_forward | |
@current_step = current_step + 1 | |
end | |
def step_back | |
@current_step = current_step - 1 | |
end | |
def step?(step) | |
@current_step.nil? || current_step + 1 == step | |
end | |
def last_step? | |
step?(self.class.total_steps) | |
end | |
def first_step? | |
step?(1) | |
end | |
def method_missing(method_name, *args, &block) | |
if /^step(\d+)\?$/ =~ method_name | |
step?($1.to_i) | |
else | |
super | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment