Skip to content

Instantly share code, notes, and snippets.

@myobie
Created March 9, 2014 11:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save myobie/9446568 to your computer and use it in GitHub Desktop.
Save myobie/9446568 to your computer and use it in GitHub Desktop.
I have this idea to create workflows for actions that need their data validated before acting and I don't want to shove it all into the model.
module Workflow
extend ActiveSupport::Concern
included do
extend ActiveModel::Naming
include ActiveModel::Validations
end
def call
if valid?
process
end
end
class WorkflowError < StandardError
def initialize(workflow)
@workflow = workflow
super
end
end
def call!
if valid?
unless process
raise WorkflowError, self
end
end
end
end
class ApproveAdjustmentWorkflow
include Workflow
def initialize(adjustment, approver)
@adjustment, @approver = adjustment, approver
end
validates_with :approver_must_be_supervisor
def process
@adjustment.update signed_off_by: @approver, state: "approved"
end
def approver_must_be_supervisor
if @adjustment.user.supervisor == @approver
errors.add(:approver, "is not supervisor")
end
end
end
class AdjustmentController < ApplicationController
def approve
@adjustment = Adjustment.find(params[:id])
approver = User.find(params.require(:signed_off_by_id))
workflow = ApproveAdjustmentWorkflow.new(adjustment, approver)
if workflow.call
flash.notice = "Approved!"
redirect_to adjustment_path(adjustment)
else
@errors = workflow.errors
render :show
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment