Module: Workflow::Adapters::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?



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

def method_missing(method, *args, &block)
  if method.to_s =~ /^transitioning_(from|to|via_event)_([\w_-]+)\?$/
    define_transitioning_method(method, *$LAST_MATCH_INFO[1..2])
    send method
  else
    super
  end
end

Instance Method Details

#can_transition?(event_id) ⇒ Boolean

Returns:

  • (Boolean)


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

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

#respond_to_missing?(method_name, _include_private = false) ⇒ Boolean

Returns:

  • (Boolean)


31
32
33
# File 'lib/workflow/adapters/active_record_validations.rb', line 31

def respond_to_missing?(method_name, _include_private = false)
  method_name.to_s =~ /^transitioning_(from|to|via_event)_([\w_-]+)\?$/
end

#within_transition(from, to, event) ⇒ 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



68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/workflow/adapters/active_record_validations.rb', line 68

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

  return yield
ensure
  @transition_context = nil
end