Sha256: db3a35f9ca27db768218b259ac92701c401b73512d86633282b901e8aa0aee5d

Contents?: true

Size: 1.67 KB

Versions: 5

Compression:

Stored size: 1.67 KB

Contents

module StateMachines::Story
  def self.included(base)
    base.extend ClassMethods
    
    base.class_eval do
      include Model::MongoDb::StateVersionAttributes
      
      attr_accessor :current_user
      
      const_set 'STATES', [:new, :tasks_defined, :active, :completed, :closed]
      const_set 'EVENTS', [:initialization, :setup_tasks, :activate, :complete]
      
      state_machine :state, initial: :new do
        event :initialization do
          transition :new => :initialized
        end
        
        event :setup_tasks do
          transition :initialized => :tasks_defined  
        end
        
        state :tasks_defined do
          #validates_associated :tasks
          validate :presence_of_tasks
        end
        
        event :activate do
          transition [:tasks_defined, :completed] => :active
        end
        
        event :complete do
          transition :active => :completed
        end
        
        event :close do
          transition :completed => :closed
        end
        
        before_transition do |object, transition|
          object.event = transition.event.to_s
          object.state_before = transition.from
        end
      end
      
      private
      
      def presence_of_tasks
        self.tasks.delete_if{|t| t.name.blank? && t.text.blank? }
        
        if tasks.select{|t| !t.valid?}.any?
          errors[:base] << I18n.t(
            'activerecord.errors.models.story.attributes.base.invalid_tasks'
          )
        end
        
        if tasks.none?
          errors[:base] << I18n.t(
            'activerecord.errors.models.story.attributes.base.missing_tasks'
          )
        end
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
voluntary-0.2.4 app/models/state_machines/story.rb
voluntary-0.2.3 app/models/state_machines/story.rb
voluntary-0.2.2 app/models/state_machines/story.rb
voluntary-0.2.1 app/models/state_machines/story.rb
voluntary-0.2.0 app/models/state_machines/story.rb