Module: Workflow::Adapter::ActiveRecordValidations

Extended by:
ActiveSupport::Concern
Defined in:
lib/workflow/adapters/active_record_validations.rb

Defined Under Namespace

Modules: ClassMethods, RevalidateOnlyAfterAttributesChange

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args, &block) ⇒ Object

Captures instance method calls of the form :transitioning_from_<state_name> and :transitioning_to_<state_name>.

For use with validators, e.g. validates :foobar, presence: true, if: :transitioning_to_some_state?



19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/workflow/adapters/active_record_validations.rb', line 19

def method_missing(method, *args, &block)
  if method.to_s =~ /^transitioning_(from|to|via_event)_([\w_-]+)\?$/
    class_eval "
    def #{method}
      transitioning? direction: '#{$~[1]}', state: '#{$~[2]}'
    end
    "
    send method
  else
    super
  end
end

Instance Method Details

#can_transition?(event_id) ⇒ Boolean

Returns:

  • (Boolean)


32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/workflow/adapters/active_record_validations.rb', line 32

def can_transition?(event_id)
  event = current_state.find_event(event_id)
  return false unless event

  from = current_state.name
  to = event.evaluate(self)

  return false unless to

  within_transition(from, to.name, event_id) do
    return valid?
  end
ensure
  errors.clear
end

#within_transition(from, to, event, &block) ⇒ Object

Executes the given block within a context that is able to give correct answers to the questions, :transitioning_from_<old_state>?. :transitioning_to_<new_state>, :transitioning_via_event_<event_name>?

For use with validators, e.g. validates :foobar, presence: true, if: :transitioning_to_some_state?

= Example:

before_transition do |from, to, name, *args| @halted = !within_transition from, to, name do valid? end end



64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/workflow/adapters/active_record_validations.rb', line 64

def within_transition(from, to, event, &block)
  begin
    @transition_context = TransitionContext.new \
      from: from,
      to: to,
      event: event,
      attributes: {},
      event_args: []

    return block.call()
  ensure
    @transition_context = nil
  end
end