Class: LcpRuby::ModelFactory::WorkflowApplicator

Inherits:
Object
  • Object
show all
Defined in:
lib/lcp_ruby/model_factory/workflow_applicator.rb

Instance Method Summary collapse

Constructor Details

#initialize(model_class, model_definition) ⇒ WorkflowApplicator

Returns a new instance of WorkflowApplicator.



4
5
6
7
# File 'lib/lcp_ruby/model_factory/workflow_applicator.rb', line 4

def initialize(model_class, model_definition)
  @model_class = model_class
  @model_definition = model_definition
end

Instance Method Details

#apply!Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/lcp_ruby/model_factory/workflow_applicator.rb', line 9

def apply!
  # Only apply if this model has a workflow-eligible enum field.
  # The actual workflow check is lazy (via Registry) because models
  # are built before Workflow::Setup runs.
  return unless has_potential_workflow_field?

  model_def = @model_definition

  # Auto-set workflow_version on record creation
  @model_class.before_create do
    next unless Workflow::Registry.available?

    workflow = Workflow::Registry.workflow_for_model(model_def.name)
    next unless workflow
    next unless respond_to?(:workflow_version=) && respond_to?(:workflow_version)
    next if workflow_version.present?

    self.workflow_version = workflow.version
  end

  # Install before_save callback that blocks direct enum changes
  # unless the _workflow_transition_active flag is set.
  # prepend: true ensures this runs before userstamps, computed fields, etc.
  @model_class.before_save(prepend: true) do
    next unless Workflow::Registry.available?

    workflow = Workflow::Registry.workflow_for_model(model_def.name)
    next unless workflow

    field = workflow.field
    next unless send("#{field}_changed?")
    next if instance_variable_get(Workflow::TransitionExecutor::TRANSITION_ACTIVE_IVAR)

    raise Workflow::TransitionDeniedError,
      "Cannot directly change '#{field}' on '#{model_def.name}'. " \
      "Use execute_transition! to change workflow state."
  end

  # Add convenience methods
  install_convenience_methods(model_def)
end