Created
March 9, 2014 11:45
-
-
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.
This file contains 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 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