wizard.rb 2.0 KB

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