wizard.rb 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. ).where(context: @steps.map(&:id))
  41. .uniq.pluck(:context)
  42. @steps.each do |s|
  43. return s unless completed.include?(s.id)
  44. end
  45. @first_step
  46. end
  47. def completed_steps?(steps)
  48. steps = [steps].flatten.uniq
  49. completed = ::UserHistory.where(
  50. acting_user_id: @user.id,
  51. action: ::UserHistory.actions[:custom_wizard_step]
  52. ).where(context: steps)
  53. .distinct.order(:context).pluck(:context)
  54. steps.sort == completed
  55. end
  56. def create_updater(step_id, fields)
  57. step = @steps.find { |s| s.id == step_id.dasherize }
  58. wizard = self
  59. CustomWizard::StepUpdater.new(@user, wizard, step, fields)
  60. end
  61. def completed?
  62. completed_steps?(@steps.map(&:id))
  63. end
  64. end