wizard.rb 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. require_dependency 'wizard/step'
  2. require_dependency 'wizard/field'
  3. require_dependency 'wizard/step_updater'
  4. require_dependency 'wizard/builder'
  5. class CustomWizard::Wizard
  6. attr_reader :steps, :user
  7. attr_accessor :id, :background, :save_submissions, :multiple_submissions
  8. def initialize(user, attrs = {})
  9. @steps = []
  10. @user = user
  11. @first_step = nil
  12. @id = attrs[:id] if attrs[:id]
  13. @save_submissions = attrs[:save_submissions] if attrs[:save_submissions]
  14. @multiple_submissions = attrs[:multiple_submissions] if attrs[:multiple_submissions]
  15. @background = attrs[:background] if attrs[:background]
  16. end
  17. def create_step(step_name)
  18. ::Wizard::Step.new(step_name)
  19. end
  20. def append_step(step)
  21. step = create_step(step) if step.is_a?(String)
  22. yield step if block_given?
  23. last_step = @steps.last
  24. @steps << step
  25. # If it's the first step
  26. if @steps.size == 1
  27. @first_step = step
  28. step.index = 0
  29. elsif last_step.present?
  30. last_step.next = step
  31. step.previous = last_step
  32. step.index = last_step.index + 1
  33. end
  34. end
  35. def start
  36. completed = ::UserHistory.where(
  37. acting_user_id: @user.id,
  38. action: ::UserHistory.actions[:custom_wizard_step]
  39. ).where(context: @steps.map(&:id))
  40. .uniq.pluck(:context)
  41. @steps.each do |s|
  42. return s unless completed.include?(s.id)
  43. end
  44. @first_step
  45. end
  46. def completed_steps?(steps)
  47. steps = [steps].flatten.uniq
  48. completed = ::UserHistory.where(
  49. acting_user_id: @user.id,
  50. action: ::UserHistory.actions[:custom_wizard_step]
  51. ).where(context: steps)
  52. .distinct.order(:context).pluck(:context)
  53. steps.sort == completed
  54. end
  55. def create_updater(step_id, fields)
  56. step = @steps.find { |s| s.id == step_id.dasherize }
  57. wizard = self
  58. CustomWizard::StepUpdater.new(@user, wizard, step, fields)
  59. end
  60. def completed?
  61. completed_steps?(@steps.map(&:id))
  62. end
  63. end