Class StateMachine::ConditionProxy
In: lib/state_machine/condition_proxy.rb
Parent: Module

Represents a type of module in which class-level methods are proxied to another class, injecting a custom :if condition along with method.

This is used for being able to automatically include conditionals which check the current state in class-level methods that have configuration options.

Examples

  class Vehicle
    class << self
      attr_accessor :validations

      def validate(options, &block)
        validations << options
      end
    end

    self.validations = []
    attr_accessor :state, :simulate

    def moving?
      self.class.validations.all? {|validation| validation[:if].call(self)}
    end
  end

In the above class, a simple set of validation behaviors have been defined. Each validation consists of a configuration like so:

  Vehicle.validate :unless => :simulate
  Vehicle.validate :if => lambda {|vehicle| ...}

In order to scope conditions, a condition proxy can be created to the Vehicle class. For example,

  proxy = StateMachine::ConditionProxy.new(Vehicle, lambda {|vehicle| vehicle.state == 'first_gear'})
  proxy.validate(:unless => :simulate)

  vehicle = Vehicle.new     # => #<Vehicle:0xb7ce491c @simulate=nil, @state=nil>
  vehicle.moving?           # => false

  vehicle.state = 'first_gear'
  vehicle.moving?           # => true

  vehicle.simulate = true
  vehicle.moving?           # => false

Methods

Included Modules

EvalHelpers

Public Class methods

Creates a new proxy to the given class, merging in the given condition

Public Instance methods

Hooks in condition-merging to methods that don‘t exist in this module

[Validate]