pax_global_header 0000666 0000000 0000000 00000000064 14447606025 0014522 g ustar 00root root 0000000 0000000 52 comment=56c9e50e2e8b3c58f13ccdb6cb09c5fe80d5b731
state_machines-activemodel-0.9.0/ 0000775 0000000 0000000 00000000000 14447606025 0017011 5 ustar 00root root 0000000 0000000 state_machines-activemodel-0.9.0/.github/ 0000775 0000000 0000000 00000000000 14447606025 0020351 5 ustar 00root root 0000000 0000000 state_machines-activemodel-0.9.0/.github/workflows/ 0000775 0000000 0000000 00000000000 14447606025 0022406 5 ustar 00root root 0000000 0000000 state_machines-activemodel-0.9.0/.github/workflows/engines.yml 0000664 0000000 0000000 00000001372 14447606025 0024564 0 ustar 00root root 0000000 0000000 name: Exotic Ruby
on:
push:
branches: [ master ]
pull_request:
branches: [ master ]
jobs:
test:
runs-on: ubuntu-latest
strategy:
matrix:
ruby-version: ['jruby', 'truffleruby']
gemfiles:
- gemfiles/active_model_6.0.gemfile
- gemfiles/active_model_6.1.gemfile
- gemfiles/active_model_7.0.gemfile
- gemfiles/active_model_edge.gemfile
env:
BUNDLE_GEMFILE: ${{ github.workspace }}/${{ matrix.gemfiles }}
steps:
- uses: actions/checkout@v3
- name: Set up Ruby
uses: ruby/setup-ruby@v1
with:
ruby-version: ${{ matrix.ruby-version }}
bundler-cache: true
- name: Run tests
run: bundle exec rake
continue-on-error: true
state_machines-activemodel-0.9.0/.github/workflows/ruby.yml 0000664 0000000 0000000 00000001372 14447606025 0024115 0 ustar 00root root 0000000 0000000 name: Ruby
on:
push:
branches: [ master ]
pull_request:
branches: [ master ]
jobs:
test:
runs-on: ubuntu-latest
strategy:
matrix:
ruby-version: ['3.0', '3.1', '3.2']
gemfiles:
- gemfiles/active_model_6.0.gemfile
- gemfiles/active_model_6.1.gemfile
- gemfiles/active_model_7.0.gemfile
- gemfiles/active_model_edge.gemfile
env:
BUNDLE_GEMFILE: ${{ github.workspace }}/${{ matrix.gemfiles }}
steps:
- uses: actions/checkout@v3
- name: Set up Ruby
uses: ruby/setup-ruby@v1
with:
ruby-version: ${{ matrix.ruby-version }}
gemfile: ${{ matrix.gemfiles }}
bundler-cache: true
- name: Run tests
run: bundle exec rake
state_machines-activemodel-0.9.0/.gitignore 0000664 0000000 0000000 00000000255 14447606025 0021003 0 ustar 00root root 0000000 0000000 *.gem
*.rbc
.bundle
.config
.yardoc
Gemfile.lock
InstalledFiles
_yardoc
coverage
doc/
lib/bundler/man
pkg
rdoc
spec/reports
tmp
*.bundle
*.so
*.o
*.a
mkmf.log
.idea/
*.lock
state_machines-activemodel-0.9.0/Appraisals 0000664 0000000 0000000 00000000506 14447606025 0021034 0 ustar 00root root 0000000 0000000 # ActiveModel integrations
appraise 'active_model_6.0' do
gem 'activemodel', '~> 6.0.3'
end
appraise 'active_model_6.1' do
gem 'activemodel', '~> 6.1.3'
end
appraise 'active_model_7.0' do
gem 'activemodel', '~> 7.0.0'
end
appraise 'active_model_edge' do
gem 'activemodel', github: 'rails/rails', branch: 'main'
end
state_machines-activemodel-0.9.0/Gemfile 0000664 0000000 0000000 00000000231 14447606025 0020300 0 ustar 00root root 0000000 0000000 source 'https://rubygems.org'
# Specify your gem's dependencies in state_machine2_activemodel.gemspec
gemspec
platforms :mri do
gem 'pry-byebug'
end
state_machines-activemodel-0.9.0/LICENSE.txt 0000664 0000000 0000000 00000002135 14447606025 0020635 0 ustar 00root root 0000000 0000000 Copyright (c) 2006-2012 Aaron Pfeifer
Copyright (c) 2014-2023 Abdelkader Boudih
MIT License
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
state_machines-activemodel-0.9.0/README.md 0000664 0000000 0000000 00000004340 14447606025 0020271 0 ustar 00root root 0000000 0000000 
[](https://codeclimate.com/github/state-machines/state_machines-activemodel)
# StateMachines ActiveModel Integration
The ActiveModel integration is useful for both standalone usage and for providing
the base implementation for ORMs which implement the ActiveModel API. This
integration adds support for validation errors and dirty attribute tracking.
## Installation
Add this line to your application's Gemfile:
gem 'state_machines-activemodel'
And then execute:
$ bundle
Or install it yourself as:
$ gem install state_machines-activemodel
## Dependencies
Active Model 5.1+
## Usage
```ruby
class Vehicle
include ActiveModel::Dirty
include ActiveModel::Validations
attr_accessor :state
define_attribute_methods [:state]
state_machine :initial => :parked do
before_transition :parked => any - :parked, :do => :put_on_seatbelt
after_transition any => :parked do |vehicle, transition|
vehicle.seatbelt = 'off'
end
around_transition :benchmark
event :ignite do
transition :parked => :idling
end
state :first_gear, :second_gear do
validates_presence_of :seatbelt_on
end
end
def put_on_seatbelt
...
end
def benchmark
...
yield
...
end
end
class VehicleObserver < ActiveModel::Observer
# Callback for :ignite event *before* the transition is performed
def before_ignite(vehicle, transition)
# log message
end
# Generic transition callback *after* the transition is performed
def after_transition(vehicle, transition)
Audit.log(vehicle, transition)
end
# Generic callback after the transition fails to perform
def after_failure_to_transition(vehicle, transition)
Audit.error(vehicle, transition)
end
end
```
## Contributing
1. Fork it ( https://github.com/state-machines/state_machines-activemodel/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create a new Pull Request
state_machines-activemodel-0.9.0/Rakefile 0000664 0000000 0000000 00000000263 14447606025 0020457 0 ustar 00root root 0000000 0000000 require 'bundler/gem_tasks'
require 'rake/testtask'
Rake::TestTask.new do |t|
t.test_files = FileList['test/*_test.rb']
end
desc 'Default: run all tests.'
task default: :test
state_machines-activemodel-0.9.0/gemfiles/ 0000775 0000000 0000000 00000000000 14447606025 0020604 5 ustar 00root root 0000000 0000000 state_machines-activemodel-0.9.0/gemfiles/active_model_6.0.gemfile 0000664 0000000 0000000 00000000244 14447606025 0025154 0 ustar 00root root 0000000 0000000 # This file was generated by Appraisal
source "https://rubygems.org"
gem "activemodel", "~> 6.0.3"
platforms :mri do
gem "pry-byebug"
end
gemspec path: "../"
state_machines-activemodel-0.9.0/gemfiles/active_model_6.1.gemfile 0000664 0000000 0000000 00000000244 14447606025 0025155 0 ustar 00root root 0000000 0000000 # This file was generated by Appraisal
source "https://rubygems.org"
gem "activemodel", "~> 6.1.3"
platforms :mri do
gem "pry-byebug"
end
gemspec path: "../"
state_machines-activemodel-0.9.0/gemfiles/active_model_7.0.gemfile 0000664 0000000 0000000 00000000244 14447606025 0025155 0 ustar 00root root 0000000 0000000 # This file was generated by Appraisal
source "https://rubygems.org"
gem "activemodel", "~> 7.0.0"
platforms :mri do
gem "pry-byebug"
end
gemspec path: "../"
state_machines-activemodel-0.9.0/gemfiles/active_model_edge.gemfile 0000664 0000000 0000000 00000000277 14447606025 0025563 0 ustar 00root root 0000000 0000000 # This file was generated by Appraisal
source "https://rubygems.org"
gem "activemodel", github: "rails/rails", branch: "main"
platforms :mri do
gem "pry-byebug"
end
gemspec path: "../"
state_machines-activemodel-0.9.0/lib/ 0000775 0000000 0000000 00000000000 14447606025 0017557 5 ustar 00root root 0000000 0000000 state_machines-activemodel-0.9.0/lib/state_machines-activemodel.rb 0000664 0000000 0000000 00000000325 14447606025 0025365 0 ustar 00root root 0000000 0000000 require 'active_support'
require 'state_machines/integrations/active_model'
ActiveSupport.on_load(:i18n) do
I18n.load_path << File.expand_path('state_machines/integrations/active_model/locale.rb', __dir__)
end
state_machines-activemodel-0.9.0/lib/state_machines/ 0000775 0000000 0000000 00000000000 14447606025 0022546 5 ustar 00root root 0000000 0000000 state_machines-activemodel-0.9.0/lib/state_machines/integrations/ 0000775 0000000 0000000 00000000000 14447606025 0025254 5 ustar 00root root 0000000 0000000 state_machines-activemodel-0.9.0/lib/state_machines/integrations/active_model.rb 0000664 0000000 0000000 00000045745 14447606025 0030253 0 ustar 00root root 0000000 0000000 require 'active_model'
require 'active_support/core_ext/hash/keys'
require 'active_support/core_ext/module/attribute_accessors.rb'
require 'state_machines'
require 'state_machines/integrations/base'
require 'state_machines/integrations/active_model/version'
module StateMachines
module Integrations #:nodoc:
# Adds support for integrating state machines with ActiveModel classes.
#
# == Examples
#
# If using ActiveModel directly within your class, then any one of the
# following features need to be included in order for the integration to be
# detected:
# * ActiveModel::Validations
#
# Below is an example of a simple state machine defined within an
# ActiveModel class:
#
# class Vehicle
# include ActiveModel::Validations
#
# attr_accessor :state
# define_attribute_methods [:state]
#
# state_machine :initial => :parked do
# event :ignite do
# transition :parked => :idling
# end
# end
# end
#
# The examples in the sections below will use the above class as a
# reference.
#
# == Actions
#
# By default, no action will be invoked when a state is transitioned. This
# means that if you want to save changes when transitioning, you must
# define the action yourself like so:
#
# class Vehicle
# include ActiveModel::Validations
# attr_accessor :state
#
# state_machine :action => :save do
# ...
# end
#
# def save
# # Save changes
# end
# end
#
# == Validations
#
# As mentioned in StateMachine::Machine#state, you can define behaviors,
# like validations, that only execute for certain states. One *important*
# caveat here is that, due to a constraint in ActiveModel's validation
# framework, custom validators will not work as expected when defined to run
# in multiple states. For example:
#
# class Vehicle
# include ActiveModel::Validations
#
# state_machine do
# ...
# state :first_gear, :second_gear do
# validate :speed_is_legal
# end
# end
# end
#
# In this case, the :speed_is_legal validation will only get run
# for the :second_gear state. To avoid this, you can define your
# custom validation like so:
#
# class Vehicle
# include ActiveModel::Validations
#
# state_machine do
# ...
# state :first_gear, :second_gear do
# validate {|vehicle| vehicle.speed_is_legal}
# end
# end
# end
#
# == Validation errors
#
# In order to hook in validation support for your model, the
# ActiveModel::Validations feature must be included. If this is included
# and an event fails to successfully fire because there are no matching
# transitions for the object, a validation error is added to the object's
# state attribute to help in determining why it failed.
#
# For example,
#
# vehicle = Vehicle.new
# vehicle.ignite # => false
# vehicle.errors.full_messages # => ["State cannot transition via \"ignite\""]
#
# In addition, if you're using the ignite! version of the event,
# then the failure reason (such as the current validation errors) will be
# included in the exception that gets raised when the event fails. For
# example, assuming there's a validation on a field called +name+ on the class:
#
# vehicle = Vehicle.new
# vehicle.ignite! # => StateMachine::InvalidTransition: Cannot transition state via :ignite from :parked (Reason(s): Name cannot be blank)
#
# === Security implications
#
# Beware that public event attributes mean that events can be fired
# whenever mass-assignment is being used. If you want to prevent malicious
# users from tampering with events through URLs / forms, the attribute
# should be protected like so:
#
# class Vehicle
# include ActiveModel::MassAssignmentSecurity
# attr_accessor :state
#
# attr_protected :state_event
# # attr_accessible ... # Alternative technique
#
# state_machine do
# ...
# end
# end
#
# If you want to only have *some* events be able to fire via mass-assignment,
# you can build two state machines (one public and one protected) like so:
#
# class Vehicle
# attr_accessor :state
#
# attr_protected :state_event # Prevent access to events in the first machine
#
# state_machine do
# # Define private events here
# end
#
# # Public machine targets the same state as the private machine
# state_machine :public_state, :attribute => :state do
# # Define public events here
# end
# end
#
# == Callbacks
#
# All before/after transition callbacks defined for ActiveModel models
# behave in the same way that other ActiveSupport callbacks behave. The
# object involved in the transition is passed in as an argument.
#
# For example,
#
# class Vehicle
# include ActiveModel::Validations
# attr_accessor :state
#
# state_machine :initial => :parked do
# before_transition any => :idling do |vehicle|
# vehicle.put_on_seatbelt
# end
#
# before_transition do |vehicle, transition|
# # log message
# end
#
# event :ignite do
# transition :parked => :idling
# end
# end
#
# def put_on_seatbelt
# ...
# end
# end
#
# Note, also, that the transition can be accessed by simply defining
# additional arguments in the callback block.
#
# == Observers
#
# In order to hook in observer support for your application, the
# ActiveModel::Observing feature must be included. This can be added by including the
# https://github.com/state-machines/state_machines-activemodel-observers gem in your
# Gemfile. Because of the way
# ActiveModel observers are designed, there is less flexibility around the
# specific transitions that can be hooked in. However, a large number of
# hooks *are* supported. For example, if a transition for a object's
# +state+ attribute changes the state from +parked+ to +idling+ via the
# +ignite+ event, the following observer methods are supported:
# * before/after/after_failure_to-_ignite_from_parked_to_idling
# * before/after/after_failure_to-_ignite_from_parked
# * before/after/after_failure_to-_ignite_to_idling
# * before/after/after_failure_to-_ignite
# * before/after/after_failure_to-_transition_state_from_parked_to_idling
# * before/after/after_failure_to-_transition_state_from_parked
# * before/after/after_failure_to-_transition_state_to_idling
# * before/after/after_failure_to-_transition_state
# * before/after/after_failure_to-_transition
#
# The following class shows an example of some of these hooks:
#
# class VehicleObserver < ActiveModel::Observer
# # Callback for :ignite event *before* the transition is performed
# def before_ignite(vehicle, transition)
# # log message
# end
#
# # Callback for :ignite event *after* the transition has been performed
# def after_ignite(vehicle, transition)
# # put on seatbelt
# end
#
# # Generic transition callback *before* the transition is performed
# def after_transition(vehicle, transition)
# Audit.log(vehicle, transition)
# end
#
# def after_failure_to_transition(vehicle, transition)
# Audit.error(vehicle, transition)
# end
# end
#
# More flexible transition callbacks can be defined directly within the
# model as described in StateMachine::Machine#before_transition
# and StateMachine::Machine#after_transition.
#
# To define a single observer for multiple state machines:
#
# class StateMachineObserver < ActiveModel::Observer
# observe Vehicle, Switch, Project
#
# def after_transition(object, transition)
# Audit.log(object, transition)
# end
# end
#
# == Internationalization
#
# Any error message that is generated from performing invalid transitions
# can be localized. The following default translations are used:
#
# en:
# activemodel:
# errors:
# messages:
# invalid: "is invalid"
# # %{value} = attribute value, %{state} = Human state name
# invalid_event: "cannot transition when %{state}"
# # %{value} = attribute value, %{event} = Human event name, %{state} = Human current state name
# invalid_transition: "cannot transition via %{event}"
#
# You can override these for a specific model like so:
#
# en:
# activemodel:
# errors:
# models:
# user:
# invalid: "is not valid"
#
# In addition to the above, you can also provide translations for the
# various states / events in each state machine. Using the Vehicle example,
# state translations will be looked for using the following keys, where
# +model_name+ = "vehicle", +machine_name+ = "state" and +state_name+ = "parked":
# * activemodel.state_machines.#{model_name}.#{machine_name}.states.#{state_name}
# * activemodel.state_machines.#{model_name}.states.#{state_name}
# * activemodel.state_machines.#{machine_name}.states.#{state_name}
# * activemodel.state_machines.states.#{state_name}
#
# Event translations will be looked for using the following keys, where
# +model_name+ = "vehicle", +machine_name+ = "state" and +event_name+ = "ignite":
# * activemodel.state_machines.#{model_name}.#{machine_name}.events.#{event_name}
# * activemodel.state_machines.#{model_name}.events.#{event_name}
# * activemodel.state_machines.#{machine_name}.events.#{event_name}
# * activemodel.state_machines.events.#{event_name}
#
# An example translation configuration might look like so:
#
# es:
# activemodel:
# state_machines:
# states:
# parked: 'estacionado'
# events:
# park: 'estacionarse'
#
# == Dirty Attribute Tracking
#
# When using the ActiveModel::Dirty extension, your model will keep track of
# any changes that are made to attributes. Depending on your ORM, an object
# will only be saved when there are attributes that have changed on the
# object. When integrating with state_machine, typically the +state+ field
# will be marked as dirty after a transition occurs. In some situations,
# however, this isn't the case.
#
# If you define loopback transitions in your state machine, the value for
# the machine's attribute (e.g. state) will not change. Unless you explicitly
# indicate so, this means that your object won't persist anything on a
# loopback. For example:
#
# class Vehicle
# include ActiveModel::Validations
# include ActiveModel::Dirty
# attr_accessor :state
#
# state_machine :initial => :parked do
# event :park do
# transition :parked => :parked, ...
# end
# end
# end
#
# If, instead, you'd like your object to always persist regardless of
# whether the value actually changed, you can do so by using the
# #{attribute}_will_change! helpers or defining a +before_transition+
# callback that actually changes an attribute on the model. For example:
#
# class Vehicle
# ...
# state_machine :initial => :parked do
# before_transition all => same do |vehicle|
# vehicle.state_will_change!
#
# # Alternative solution, updating timestamp
# # vehicle.updated_at = Time.current
# end
# end
# end
#
# == Creating new integrations
#
# If you want to integrate state_machine with an ORM that implements parts
# or all of the ActiveModel API, only the machine defaults need to be
# specified. Otherwise, the implementation is similar to any other
# integration.
#
# For example,
#
# module StateMachine::Integrations::MyORM
# include ActiveModel
#
# mattr_accessor(:defaults) { :action => :persist }
#
# def self.matches?(klass)
# defined?(::MyORM::Base) && klass <= ::MyORM::Base
# end
#
# protected
#
# def runs_validations_on_action?
# action == :persist
# end
# end
#
# If you wish to implement other features, such as attribute initialization
# with protected attributes, named scopes, or database transactions, you
# must add these independent of the ActiveModel integration. See the
# ActiveRecord implementation for examples of these customizations.
module ActiveModel
include Base
@defaults = {}
# Classes that include ActiveModel::Validations
# will automatically use the ActiveModel integration.
def self.matching_ancestors
[::ActiveModel, ::ActiveModel::Validations]
end
# Adds a validation error to the given object
def invalidate(object, attribute, message, values = [])
if supports_validations?
attribute = self.attribute(attribute)
options = values.reduce({}) do |h, (key, value)|
h[key] = value
h
end
default_options = default_error_message_options(object, attribute, message)
object.errors.add(attribute, message, **options, **default_options)
end
end
# Describes the current validation errors on the given object. If none
# are specific, then the default error is interpeted as a "halt".
def errors_for(object)
object.errors.empty? ? 'Transition halted' : object.errors.full_messages * ', '
end
# Resets any errors previously added when invalidating the given object
def reset(object)
object.errors.clear if supports_validations?
end
# Runs state events around the object's validation process
def around_validation(object)
object.class.state_machines.transitions(object, action, after: false).perform { yield }
end
protected
def define_state_initializer
define_helper :instance, <<-end_eval, __FILE__, __LINE__ + 1
def initialize(params = {})
params.transform_keys! do |key|
self.class.attribute_aliases[key.to_s] || key.to_s
end if self.class.respond_to?(:attribute_aliases)
self.class.state_machines.initialize_states(self, {}, params) { super }
end
end_eval
end
# Whether validations are supported in the integration. Only true if
# the ActiveModel feature is enabled on the owner class.
def supports_validations?
defined?(::ActiveModel::Validations) && owner_class <= ::ActiveModel::Validations
end
# Do validations run when the action configured this machine is
# invoked? This is used to determine whether to fire off attribute-based
# event transitions when the action is run.
def runs_validations_on_action?
false
end
# Gets the terminator to use for callbacks
def callback_terminator
@terminator ||= ->(result) { result == false }
end
# Determines the base scope to use when looking up translations
def i18n_scope(klass)
klass.i18n_scope
end
# The default options to use when generating messages for validation
# errors
def default_error_message_options(_object, _attribute, message)
{ message: @messages[message] }
end
# Translates the given key / value combo. Translation keys are looked
# up in the following order:
# * #{i18n_scope}.state_machines.#{model_name}.#{machine_name}.#{plural_key}.#{value}
# * #{i18n_scope}.state_machines.#{model_name}.#{plural_key}.#{value}
# * #{i18n_scope}.state_machines.#{machine_name}.#{plural_key}.#{value}
# * #{i18n_scope}.state_machines.#{plural_key}.#{value}
#
# If no keys are found, then the humanized value will be the fallback.
def translate(klass, key, value)
ancestors = ancestors_for(klass)
group = key.to_s.pluralize
value = value ? value.to_s : 'nil'
# Generate all possible translation keys
translations = ancestors.map { |ancestor| :"#{ancestor.model_name.to_s.underscore}.#{name}.#{group}.#{value}" }
translations.concat(ancestors.map { |ancestor| :"#{ancestor.model_name.to_s.underscore}.#{group}.#{value}" })
translations.concat([:"#{name}.#{group}.#{value}", :"#{group}.#{value}", value.humanize.downcase])
I18n.translate(translations.shift, default: translations, scope: [i18n_scope(klass), :state_machines])
end
# Build a list of ancestors for the given class to use when
# determining which localization key to use for a particular string.
def ancestors_for(klass)
klass.lookup_ancestors
end
# Skips defining reader/writer methods since this is done automatically
def define_state_accessor
name = self.name
owner_class.validates_each(attribute) do |object|
machine = object.class.state_machine(name)
machine.invalidate(object, :state, :invalid) unless machine.states.match(object)
end if supports_validations?
end
# Adds hooks into validation for automatically firing events
def define_action_helpers
super
define_validation_hook if runs_validations_on_action?
end
# Hooks into validations by defining around callbacks for the
# :validation event
def define_validation_hook
owner_class.set_callback(:validation, :around, self, prepend: true)
end
# Creates a new callback in the callback chain, always inserting it
# before the default Observer callbacks that were created after
# initialization.
def add_callback(type, options, &block)
options[:terminator] = callback_terminator
super
end
# Configures new states with the built-in humanize scheme
def add_states(*)
super.each do |new_state|
new_state.human_name = ->(state, klass) { translate(klass, :state, state.name) }
end
end
# Configures new event with the built-in humanize scheme
def add_events(*)
super.each do |new_event|
new_event.human_name = ->(event, klass) { translate(klass, :event, event.name) }
end
end
end
register(ActiveModel)
end
end
state_machines-activemodel-0.9.0/lib/state_machines/integrations/active_model/ 0000775 0000000 0000000 00000000000 14447606025 0027707 5 ustar 00root root 0000000 0000000 state_machines-activemodel-0.9.0/lib/state_machines/integrations/active_model/locale.rb 0000664 0000000 0000000 00000000532 14447606025 0031473 0 ustar 00root root 0000000 0000000 { en: {
activemodel: {
errors: {
messages: {
invalid: StateMachines::Machine.default_messages[:invalid],
invalid_event: StateMachines::Machine.default_messages[:invalid_event] % ['%{state}'],
invalid_transition: StateMachines::Machine.default_messages[:invalid_transition] % ['%{event}']
}
}
}
} }
state_machines-activemodel-0.9.0/lib/state_machines/integrations/active_model/version.rb 0000664 0000000 0000000 00000000154 14447606025 0031721 0 ustar 00root root 0000000 0000000 module StateMachines
module Integrations
module ActiveModel
VERSION = '0.9.0'
end
end
end
state_machines-activemodel-0.9.0/state_machines-activemodel.gemspec 0000664 0000000 0000000 00000002300 14447606025 0025632 0 ustar 00root root 0000000 0000000 require_relative 'lib/state_machines/integrations/active_model/version'
Gem::Specification.new do |spec|
spec.name = 'state_machines-activemodel'
spec.version = StateMachines::Integrations::ActiveModel::VERSION
spec.authors = ['Abdelkader Boudih', 'Aaron Pfeifer']
spec.email = %w(terminale@gmail.com aaron@pluginaweek.org)
spec.summary = 'ActiveModel integration for State Machines'
spec.description = 'Adds support for creating state machines for attributes on ActiveModel'
spec.homepage = 'https://github.com/state-machines/state_machines-activemodel'
spec.license = 'MIT'
spec.files = Dir.glob('{lib}/**/*') + %w(LICENSE.txt README.md)
spec.test_files = Dir.glob('test/**/*_test.rb')
spec.require_paths = ['lib']
spec.required_ruby_version = '>= 3.0.0'
spec.add_dependency 'state_machines', '>= 0.6.0'
spec.add_dependency 'activemodel', '>= 6.0'
spec.add_development_dependency 'bundler', '>= 1.6'
spec.add_development_dependency 'rake', '>= 10'
spec.add_development_dependency 'appraisal', '>= 1'
spec.add_development_dependency 'minitest', '~> 5.4'
spec.add_development_dependency 'minitest-reporters'
end
state_machines-activemodel-0.9.0/test/ 0000775 0000000 0000000 00000000000 14447606025 0017770 5 ustar 00root root 0000000 0000000 state_machines-activemodel-0.9.0/test/files/ 0000775 0000000 0000000 00000000000 14447606025 0021072 5 ustar 00root root 0000000 0000000 state_machines-activemodel-0.9.0/test/files/en.yml 0000664 0000000 0000000 00000000134 14447606025 0022215 0 ustar 00root root 0000000 0000000 en:
activemodel:
errors:
messages:
invalid_transition: "cannot %{event}" state_machines-activemodel-0.9.0/test/integration_test.rb 0000664 0000000 0000000 00000001605 14447606025 0023701 0 ustar 00root root 0000000 0000000 require_relative 'test_helper'
class IntegrationTest < BaseTestCase
def test_should_be_registered
assert_includes StateMachines::Integrations.list, StateMachines::Integrations::ActiveModel
end
def test_should_register_one_integration
assert_equal 1, StateMachines::Integrations.list.size
end
def test_should_have_an_integration_name
assert_equal :active_model, StateMachines::Integrations::ActiveModel.integration_name
end
def test_should_match_if_class_includes_validations_feature
assert StateMachines::Integrations::ActiveModel.matches?(new_model { include ActiveModel::Validations })
end
def test_should_not_match_if_class_does_not_include_active_model_features
refute StateMachines::Integrations::ActiveModel.matches?(new_model)
end
def test_should_have_no_defaults
assert_equal({}, StateMachines::Integrations::ActiveModel.defaults)
end
end
state_machines-activemodel-0.9.0/test/machine_by_default_test.rb 0000664 0000000 0000000 00000001076 14447606025 0025162 0 ustar 00root root 0000000 0000000 require_relative 'test_helper'
class MachineByDefaultTest < BaseTestCase
def setup
@model = new_model
@machine = StateMachines::Machine.new(@model, integration: :active_model)
end
def test_should_not_have_action
assert_nil @machine.action
end
def test_should_use_transactions
assert_equal true, @machine.use_transactions
end
def test_should_not_have_any_before_callbacks
assert_equal 0, @machine.callbacks[:before].size
end
def test_should_not_have_any_after_callbacks
assert_equal 0, @machine.callbacks[:after].size
end
end
state_machines-activemodel-0.9.0/test/machine_errors_test.rb 0000664 0000000 0000000 00000001145 14447606025 0024355 0 ustar 00root root 0000000 0000000 require_relative 'test_helper'
class MachineErrorsTest < BaseTestCase
def setup
@model = new_model { include ActiveModel::Validations }
@machine = StateMachines::Machine.new(@model)
@record = @model.new
end
def test_should_be_able_to_describe_current_errors
@record.errors.add(:id, 'cannot be blank')
@record.errors.add(:state, 'is invalid')
assert_equal ['Id cannot be blank', 'State is invalid'], @machine.errors_for(@record).split(', ').sort
end
def test_should_describe_as_halted_with_no_errors
assert_equal 'Transition halted', @machine.errors_for(@record)
end
end
state_machines-activemodel-0.9.0/test/machine_multiple_test.rb 0000664 0000000 0000000 00000001025 14447606025 0024671 0 ustar 00root root 0000000 0000000 require_relative 'test_helper'
class MachineMultipleTest < BaseTestCase
def setup
@model = new_model do
model_attribute :status
end
@state_machine = StateMachines::Machine.new(@model, initial: :parked, integration: :active_model)
@status_machine = StateMachines::Machine.new(@model, :status, initial: :idling, integration: :active_model)
end
def test_should_should_initialize_each_state
record = @model.new
assert_equal 'parked', record.state
assert_equal 'idling', record.status
end
end
state_machines-activemodel-0.9.0/test/machine_with_callbacks_test.rb 0000664 0000000 0000000 00000006327 14447606025 0026022 0 ustar 00root root 0000000 0000000 require_relative 'test_helper'
class MachineWithCallbacksTest < BaseTestCase
def setup
@model = new_model
@machine = StateMachines::Machine.new(@model, initial: :parked, integration: :active_model)
@machine.other_states :idling
@machine.event :ignite
@record = @model.new(state: 'parked')
@transition = StateMachines::Transition.new(@record, @machine, :ignite, :parked, :idling)
end
def test_should_run_before_callbacks
called = false
@machine.before_transition { called = true }
@transition.perform
assert called
end
def test_should_pass_record_to_before_callbacks_with_one_argument
record = nil
@machine.before_transition { |arg| record = arg }
@transition.perform
assert_equal @record, record
end
def test_should_pass_record_and_transition_to_before_callbacks_with_multiple_arguments
callback_args = nil
@machine.before_transition { |*args| callback_args = args }
@transition.perform
assert_equal [@record, @transition], callback_args
end
def test_should_run_before_callbacks_outside_the_context_of_the_record
context = nil
@machine.before_transition { context = self }
@transition.perform
assert_equal self, context
end
def test_should_run_after_callbacks
called = false
@machine.after_transition { called = true }
@transition.perform
assert called
end
def test_should_pass_record_to_after_callbacks_with_one_argument
record = nil
@machine.after_transition { |arg| record = arg }
@transition.perform
assert_equal @record, record
end
def test_should_pass_record_and_transition_to_after_callbacks_with_multiple_arguments
callback_args = nil
@machine.after_transition { |*args| callback_args = args }
@transition.perform
assert_equal [@record, @transition], callback_args
end
def test_should_run_after_callbacks_outside_the_context_of_the_record
context = nil
@machine.after_transition { context = self }
@transition.perform
assert_equal self, context
end
def test_should_run_around_callbacks
before_called = false
after_called = false
ensure_called = 0
@machine.around_transition do |block|
before_called = true
begin
block.call
ensure
ensure_called += 1
end
after_called = true
end
@transition.perform
assert before_called
assert after_called
assert_equal ensure_called, 1
end
def test_should_include_transition_states_in_known_states
@machine.before_transition to: :first_gear, do: lambda {}
assert_equal [:parked, :idling, :first_gear], @machine.states.map { |state| state.name }
end
def test_should_allow_symbolic_callbacks
callback_args = nil
klass = class << @record
self
end
klass.send(:define_method, :after_ignite) do |*args|
callback_args = args
end
@machine.before_transition(:after_ignite)
@transition.perform
assert_equal [@transition], callback_args
end
def test_should_allow_string_callbacks
class << @record
attr_reader :callback_result
end
@machine.before_transition('@callback_result = [1, 2, 3]')
@transition.perform
assert_equal [1, 2, 3], @record.callback_result
end
end
machine_with_dirty_attribute_and_custom_attributes_during_loopback_test.rb 0000664 0000000 0000000 00000001445 14447606025 0037142 0 ustar 00root root 0000000 0000000 state_machines-activemodel-0.9.0/test require_relative 'test_helper'
class MachineWithDirtyAttributeAndCustomAttributesDuringLoopbackTest < BaseTestCase
def setup
@model = new_model do
include ActiveModel::Dirty
model_attribute :status
define_attribute_methods [:status]
def save
super.tap do
changes_applied
end
end
end
@machine = StateMachines::Machine.new(@model, :status, initial: :parked)
@machine.event :park
@record = @model.create
@transition = StateMachines::Transition.new(@record, @machine, :park, :parked, :parked)
@transition.perform
end
def test_should_not_include_state_in_changed_attributes
assert_equal [], @record.changed
end
def test_should_not_track_attribute_changes
assert_nil @record.changes['status']
end
end
state_machines-activemodel-0.9.0/test/machine_with_dirty_attribute_and_state_events_test.rb 0000664 0000000 0000000 00000001247 14447606025 0032723 0 ustar 00root root 0000000 0000000 require_relative 'test_helper'
class MachineWithDirtyAttributeAndStateEventsTest < BaseTestCase
def setup
@model = new_model do
include ActiveModel::Dirty
define_attribute_methods [:state]
def save
super.tap do
changes_applied
end
end
end
@machine = StateMachines::Machine.new(@model, action: :save, initial: :parked)
@machine.event :ignite
@record = @model.create
@record.state_event = 'ignite'
end
def test_should_not_include_state_in_changed_attributes
assert_equal [], @record.changed
end
def test_should_not_track_attribute_change
assert_nil @record.changes['state']
end
end
state_machines-activemodel-0.9.0/test/machine_with_dirty_attributes_and_custom_attribute_test.rb 0000664 0000000 0000000 00000002100 14447606025 0033764 0 ustar 00root root 0000000 0000000 require_relative 'test_helper'
class MachineWithDirtyAttributesAndCustomAttributeTest < BaseTestCase
def setup
@model = new_model do
include ActiveModel::Dirty
model_attribute :status
define_attribute_methods [:status]
def save
super.tap do
changes_applied
end
end
end
@machine = StateMachines::Machine.new(@model, :status, initial: :parked)
@machine.event :ignite
@machine.state :idling
@record = @model.create
@transition = StateMachines::Transition.new(@record, @machine, :ignite, :parked, :idling)
@transition.perform
end
def test_should_include_state_in_changed_attributes
assert_equal %w(status), @record.changed
end
def test_should_track_attribute_change
assert_equal %w(parked idling), @record.changes['status']
end
def test_should_not_reset_changes_on_multiple_transitions
transition = StateMachines::Transition.new(@record, @machine, :ignite, :idling, :idling)
transition.perform
assert_equal %w(parked idling), @record.changes['status']
end
end
state_machines-activemodel-0.9.0/test/machine_with_dirty_attributes_during_loopback_test.rb 0000664 0000000 0000000 00000001352 14447606025 0032717 0 ustar 00root root 0000000 0000000 require_relative 'test_helper'
class MachineWithDirtyAttributesDuringLoopbackTest < BaseTestCase
def setup
@model = new_model do
include ActiveModel::Dirty
define_attribute_methods [:state]
def save
super.tap do
changes_applied
end
end
end
@machine = StateMachines::Machine.new(@model, initial: :parked)
@machine.event :park
@record = @model.create
@transition = StateMachines::Transition.new(@record, @machine, :park, :parked, :parked)
@transition.perform
end
def test_should_not_include_state_in_changed_attributes
assert_equal [], @record.changed
end
def test_should_not_track_attribute_changes
assert_nil @record.changes['state']
end
end
state_machines-activemodel-0.9.0/test/machine_with_dirty_attributes_test.rb 0000664 0000000 0000000 00000002003 14447606025 0027467 0 ustar 00root root 0000000 0000000 require_relative 'test_helper'
class MachineWithDirtyAttributesTest < BaseTestCase
def setup
@model = new_model do
include ActiveModel::Dirty
define_attribute_methods [:state]
def save
super.tap do
changes_applied
end
end
end
@machine = StateMachines::Machine.new(@model, initial: :parked)
@machine.event :ignite
@machine.state :idling
@record = @model.create
@transition = StateMachines::Transition.new(@record, @machine, :ignite, :parked, :idling)
@transition.perform
end
def test_should_include_state_in_changed_attributes
assert_equal %w(state), @record.changed
end
def test_should_track_attribute_change
assert_equal %w(parked idling), @record.changes['state']
end
def test_should_not_reset_changes_on_multiple_transitions
transition = StateMachines::Transition.new(@record, @machine, :ignite, :idling, :idling)
transition.perform
assert_equal %w(parked idling), @record.changes['state']
end
end
state_machines-activemodel-0.9.0/test/machine_with_dynamic_initial_state_test.rb 0000664 0000000 0000000 00000000622 14447606025 0030430 0 ustar 00root root 0000000 0000000 require_relative 'test_helper'
class MachineWithDynamicInitialStateTest < BaseTestCase
def setup
@model = new_model
@machine = StateMachines::Machine.new(@model, initial: lambda { |_object| :parked }, integration: :active_model)
@machine.state :parked
end
def test_should_set_initial_state_on_created_object
record = @model.new
assert_equal 'parked', record.state
end
end
state_machines-activemodel-0.9.0/test/machine_with_events_test.rb 0000664 0000000 0000000 00000000460 14447606025 0025377 0 ustar 00root root 0000000 0000000 require_relative 'test_helper'
class MachineWithEventsTest < BaseTestCase
def setup
@model = new_model
@machine = StateMachines::Machine.new(@model)
@machine.event :shift_up
end
def test_should_humanize_name
assert_equal 'shift up', @machine.event(:shift_up).human_name
end
end
state_machines-activemodel-0.9.0/test/machine_with_failed_after_callbacks_test.rb 0000664 0000000 0000000 00000001716 14447606025 0030504 0 ustar 00root root 0000000 0000000 require_relative 'test_helper'
class MachineWithFailedAfterCallbacksTest < BaseTestCase
def setup
@callbacks = []
@model = new_model
@machine = StateMachines::Machine.new(@model, integration: :active_model)
@machine.state :parked, :idling
@machine.event :ignite
@machine.after_transition { @callbacks << :after_1; false }
@machine.after_transition { @callbacks << :after_2 }
@machine.around_transition { |block| @callbacks << :around_before; block.call; @callbacks << :around_after }
@record = @model.new(state: 'parked')
@transition = StateMachines::Transition.new(@record, @machine, :ignite, :parked, :idling)
@result = @transition.perform
end
def test_should_be_successful
assert @result
end
def test_should_change_current_state
assert_equal 'idling', @record.state
end
def test_should_not_run_further_after_callbacks
assert_equal [:around_before, :around_after, :after_1], @callbacks
end
end
state_machines-activemodel-0.9.0/test/machine_with_failed_before_callbacks_test.rb 0000664 0000000 0000000 00000001756 14447606025 0030651 0 ustar 00root root 0000000 0000000 require_relative 'test_helper'
class MachineWithFailedBeforeCallbacksTest < BaseTestCase
def setup
@callbacks = []
@model = new_model
@machine = StateMachines::Machine.new(@model, integration: :active_model)
@machine.state :parked, :idling
@machine.event :ignite
@machine.before_transition { @callbacks << :before_1; false }
@machine.before_transition { @callbacks << :before_2 }
@machine.after_transition { @callbacks << :after }
@machine.around_transition { |block| @callbacks << :around_before; block.call; @callbacks << :around_after }
@record = @model.new(state: 'parked')
@transition = StateMachines::Transition.new(@record, @machine, :ignite, :parked, :idling)
@result = @transition.perform
end
def test_should_not_be_successful
refute @result
end
def test_should_not_change_current_state
assert_equal 'parked', @record.state
end
def test_should_not_run_further_callbacks
assert_equal [:before_1], @callbacks
end
end
state_machines-activemodel-0.9.0/test/machine_with_initialized_aliased_attribute_test.rb 0000664 0000000 0000000 00000001705 14447606025 0032150 0 ustar 00root root 0000000 0000000 require_relative 'test_helper'
class MachineWithInitializedAliasedAttributeTest < BaseTestCase
def test_should_match_original_attribute_value_with_attribute_methods
model = new_model do
include ActiveModel::AttributeMethods
alias_attribute :custom_status, :state
end
machine = StateMachines::Machine.new(model, initial: :parked, integration: :active_model)
machine.other_states(:started)
record = model.new(custom_status: 'started')
refute record.state?(:parked)
assert record.state?(:started)
end
def test_should_not_match_original_attribute_value_without_attribute_methods
model = new_model do
alias_attribute :custom_status, :state
end
machine = StateMachines::Machine.new(model, initial: :parked, integration: :active_model)
machine.other_states(:started)
record = model.new(custom_status: 'started')
assert record.state?(:parked)
refute record.state?(:started)
end
end
state_machines-activemodel-0.9.0/test/machine_with_initialized_state_test.rb 0000664 0000000 0000000 00000001651 14447606025 0027603 0 ustar 00root root 0000000 0000000 require_relative 'test_helper'
class MachineWithInitializedStateTest < BaseTestCase
def setup
@model = new_model
@machine = StateMachines::Machine.new(@model, initial: :parked, integration: :active_model)
@machine.state :idling
end
def test_should_allow_nil_initial_state_when_static
@machine.state nil
record = @model.new(state: nil)
assert_nil record.state
end
def test_should_allow_nil_initial_state_when_dynamic
@machine.state nil
@machine.initial_state = -> { :parked }
record = @model.new(state: nil)
assert_nil record.state
end
def test_should_allow_different_initial_state_when_static
record = @model.new(state: 'idling')
assert_equal 'idling', record.state
end
def test_should_allow_different_initial_state_when_dynamic
@machine.initial_state = -> { :parked }
record = @model.new(state: 'idling')
assert_equal 'idling', record.state
end
end
state_machines-activemodel-0.9.0/test/machine_with_internationalization_test.rb 0000664 0000000 0000000 00000013620 14447606025 0030342 0 ustar 00root root 0000000 0000000 require_relative 'test_helper'
require 'i18n'
class MachineWithInternationalizationTest < BaseTestCase
def setup
I18n.backend = I18n::Backend::Simple.new
@model = new_model { include ActiveModel::Validations }
end
def test_should_use_defaults
I18n.backend.store_translations(:en,
activemodel: { errors: { messages: { invalid_transition: 'cannot %{event}' } } }
)
machine = StateMachines::Machine.new(@model, action: :save)
machine.state :parked, :idling
machine.event :ignite
record = @model.new(state: 'idling')
machine.invalidate(record, :state, :invalid_transition, [[:event, 'ignite']])
assert_equal ['State cannot transition via "ignite"'], record.errors.full_messages
end
def test_should_allow_customized_error_key
I18n.backend.store_translations(:en,
activemodel: { errors: { messages: { bad_transition: 'cannot %{event}' } } }
)
machine = StateMachines::Machine.new(@model, action: :save, messages: { invalid_transition: :bad_transition })
machine.state :parked, :idling
record = @model.new
record.state = 'idling'
machine.invalidate(record, :state, :invalid_transition, [[:event, 'ignite']])
assert_equal ['State cannot ignite'], record.errors.full_messages
end
def test_should_allow_customized_error_string
machine = StateMachines::Machine.new(@model, action: :save, messages: { invalid_transition: 'cannot %{event}' })
machine.state :parked, :idling
record = @model.new(state: 'idling')
machine.invalidate(record, :state, :invalid_transition, [[:event, 'ignite']])
assert_equal ['State cannot ignite'], record.errors.full_messages
end
def test_should_allow_customized_state_key_scoped_to_class_and_machine
I18n.backend.store_translations(:en,
activemodel: { state_machines: { :'foo' => { state: { states: { parked: 'shutdown' } } } } }
)
machine = StateMachines::Machine.new(@model)
machine.state :parked
assert_equal 'shutdown', machine.state(:parked).human_name
end
def test_should_allow_customized_state_key_scoped_to_class
I18n.backend.store_translations(:en,
activemodel: { state_machines: { :'foo' => { states: { parked: 'shutdown' } } } }
)
machine = StateMachines::Machine.new(@model)
machine.state :parked
assert_equal 'shutdown', machine.state(:parked).human_name
end
def test_should_allow_customized_state_key_scoped_to_machine
I18n.backend.store_translations(:en,
activemodel: { state_machines: { state: { states: { parked: 'shutdown' } } } }
)
machine = StateMachines::Machine.new(@model)
machine.state :parked
assert_equal 'shutdown', machine.state(:parked).human_name
end
def test_should_allow_customized_state_key_unscoped
I18n.backend.store_translations(:en,
activemodel: { state_machines: { states: { parked: 'shutdown' } } }
)
machine = StateMachines::Machine.new(@model)
machine.state :parked
assert_equal 'shutdown', machine.state(:parked).human_name
end
def test_should_support_nil_state_key
I18n.backend.store_translations(:en,
activemodel: { state_machines: { states: { nil: 'empty' } } }
)
machine = StateMachines::Machine.new(@model)
assert_equal 'empty', machine.state(nil).human_name
end
def test_should_allow_customized_event_key_scoped_to_class_and_machine
I18n.backend.store_translations(:en,
activemodel: { state_machines: { :'foo' => { state: { events: { park: 'stop' } } } } }
)
machine = StateMachines::Machine.new(@model)
machine.event :park
assert_equal 'stop', machine.event(:park).human_name
end
def test_should_allow_customized_event_key_scoped_to_class
I18n.backend.store_translations(:en,
activemodel: { state_machines: { :'foo' => { events: { park: 'stop' } } } }
)
machine = StateMachines::Machine.new(@model)
machine.event :park
assert_equal 'stop', machine.event(:park).human_name
end
def test_should_allow_customized_event_key_scoped_to_machine
I18n.backend.store_translations(:en,
activemodel: { state_machines: { state: { events: { park: 'stop' } } } }
)
machine = StateMachines::Machine.new(@model)
machine.event :park
assert_equal 'stop', machine.event(:park).human_name
end
def test_should_allow_customized_event_key_unscoped
I18n.backend.store_translations(:en,
activemodel: { state_machines: { events: { park: 'stop' } } }
)
machine = StateMachines::Machine.new(@model)
machine.event :park
assert_equal 'stop', machine.event(:park).human_name
end
def test_should_have_locale_once_in_load_path
assert_equal 1, I18n.load_path.select { |path| path =~ %r{active_model/locale\.rb$} }.length
end
def test_should_prefer_other_locales_first
@original_load_path = I18n.load_path
I18n.backend = I18n::Backend::Simple.new
I18n.load_path = [File.dirname(__FILE__) + '/files/en.yml']
machine = StateMachines::Machine.new(@model)
machine.state :parked, :idling
machine.event :ignite
record = @model.new(state: 'idling')
machine.invalidate(record, :state, :invalid_transition, [[:event, 'ignite']])
assert_equal ['State cannot ignite'], record.errors.full_messages
ensure
I18n.load_path = @original_load_path
end
end
state_machines-activemodel-0.9.0/test/machine_with_model_state_attribute_test.rb 0000664 0000000 0000000 00000001561 14447606025 0030461 0 ustar 00root root 0000000 0000000 require_relative 'test_helper'
class MachineWithModelStateAttributeTest < BaseTestCase
def setup
@model = new_model
@machine = StateMachines::Machine.new(@model, initial: :parked, integration: :active_model)
@machine.other_states(:idling)
@record = @model.new
end
def test_should_have_an_attribute_predicate
assert @record.respond_to?(:state?)
end
def test_should_raise_exception_for_predicate_without_parameters
assert_raises(ArgumentError) { @record.state? }
end
def test_should_return_false_for_predicate_if_does_not_match_current_value
assert !@record.state?(:idling)
end
def test_should_return_true_for_predicate_if_matches_current_value
assert @record.state?(:parked)
end
def test_should_raise_exception_for_predicate_if_invalid_state_specified
assert_raises(IndexError) { @record.state?(:invalid) }
end
end
state_machines-activemodel-0.9.0/test/machine_with_non_model_state_attribute_undefined_test.rb 0000664 0000000 0000000 00000001246 14447606025 0033354 0 ustar 00root root 0000000 0000000 require_relative 'test_helper'
class MachineWithNonModelStateAttributeUndefinedTest < BaseTestCase
def setup
@model = new_model do
def initialize
end
end
@machine = StateMachines::Machine.new(@model, :status, initial: :parked, integration: :active_model)
@machine.other_states(:idling)
@record = @model.new
end
def test_should_not_define_a_reader_attribute_for_the_attribute
assert !@record.respond_to?(:status)
end
def test_should_not_define_a_writer_attribute_for_the_attribute
assert !@record.respond_to?(:status=)
end
def test_should_define_an_attribute_predicate
assert @record.respond_to?(:status?)
end
end
state_machines-activemodel-0.9.0/test/machine_with_state_driven_validations_test.rb 0000664 0000000 0000000 00000001552 14447606025 0031162 0 ustar 00root root 0000000 0000000 require_relative 'test_helper'
class MachineWithStateDrivenValidationsTest < BaseTestCase
def setup
@model = new_model do
include ActiveModel::Validations
attr_accessor :seatbelt
end
@machine = StateMachines::Machine.new(@model)
@machine.state :first_gear, :second_gear do
validates_presence_of :seatbelt
end
@machine.other_states :parked
end
def test_should_be_valid_if_validation_fails_outside_state_scope
record = @model.new(state: 'parked', seatbelt: nil)
assert record.valid?
end
def test_should_be_invalid_if_validation_fails_within_state_scope
record = @model.new(state: 'first_gear', seatbelt: nil)
assert !record.valid?
end
def test_should_be_valid_if_validation_succeeds_within_state_scope
record = @model.new(state: 'second_gear', seatbelt: true)
assert record.valid?
end
end
state_machines-activemodel-0.9.0/test/machine_with_states_test.rb 0000664 0000000 0000000 00000000466 14447606025 0025404 0 ustar 00root root 0000000 0000000 require_relative 'test_helper'
class MachineWithStatesTest < BaseTestCase
def setup
@model = new_model
@machine = StateMachines::Machine.new(@model)
@machine.state :first_gear
end
def test_should_humanize_name
assert_equal 'first gear', @machine.state(:first_gear).human_name
end
end
state_machines-activemodel-0.9.0/test/machine_with_static_initial_state_test.rb 0000664 0000000 0000000 00000000541 14447606025 0030273 0 ustar 00root root 0000000 0000000 require_relative 'test_helper'
class MachineWithStaticInitialStateTest < BaseTestCase
def setup
@model = new_model
@machine = StateMachines::Machine.new(@model, initial: :parked, integration: :active_model)
end
def test_should_set_initial_state_on_created_object
record = @model.new
assert_equal 'parked', record.state
end
end
state_machines-activemodel-0.9.0/test/machine_with_validations_and_custom_attribute_test.rb 0000664 0000000 0000000 00000001061 14447606025 0032705 0 ustar 00root root 0000000 0000000 require_relative 'test_helper'
class MachineWithValidationsAndCustomAttributeTest < BaseTestCase
def setup
@model = new_model { include ActiveModel::Validations }
@machine = StateMachines::Machine.new(@model, :status, attribute: :state)
@machine.state :parked
@record = @model.new
end
def test_should_add_validation_errors_to_custom_attribute
@record.state = 'invalid'
assert !@record.valid?
assert_equal ['State is invalid'], @record.errors.full_messages
@record.state = 'parked'
assert @record.valid?
end
end
state_machines-activemodel-0.9.0/test/machine_with_validations_test.rb 0000664 0000000 0000000 00000002415 14447606025 0026412 0 ustar 00root root 0000000 0000000 require_relative 'test_helper'
class MachineWithValidationsTest < BaseTestCase
def setup
@model = new_model { include ActiveModel::Validations }
@machine = StateMachines::Machine.new(@model, action: :save)
@machine.state :parked
@record = @model.new
end
def test_should_invalidate_using_errors
I18n.backend = I18n::Backend::Simple.new if Object.const_defined?(:I18n)
@record.state = 'parked'
@machine.invalidate(@record, :state, :invalid_transition, [[:event, 'park']])
assert_equal ['State cannot transition via "park"'], @record.errors.full_messages
end
def test_should_auto_prefix_custom_attributes_on_invalidation
@machine.invalidate(@record, :event, :invalid)
assert_equal ['State event is invalid'], @record.errors.full_messages
end
def test_should_clear_errors_on_reset
@record.state = 'parked'
@record.errors.add(:state, 'is invalid')
@machine.reset(@record)
assert_equal [], @record.errors.full_messages
end
def test_should_be_valid_if_state_is_known
@record.state = 'parked'
assert @record.valid?
end
def test_should_not_be_valid_if_state_is_unknown
@record.state = 'invalid'
assert !@record.valid?
assert_equal ['State is invalid'], @record.errors.full_messages
end
end
state_machines-activemodel-0.9.0/test/test_helper.rb 0000664 0000000 0000000 00000002455 14447606025 0022641 0 ustar 00root root 0000000 0000000 begin
require 'pry-byebug'
rescue LoadError
end
require 'state_machines-activemodel'
require 'minitest/autorun'
require 'minitest/reporters'
require 'active_support/all'
Minitest::Reporters.use! [Minitest::Reporters::ProgressReporter.new]
I18n.enforce_available_locales = true
class BaseTestCase < MiniTest::Test
protected
# Creates a new ActiveModel model (and the associated table)
def new_model(&block)
# Simple ActiveModel superclass
parent = Class.new do
def self.model_attribute(name)
define_method(name) { instance_variable_defined?("@#{name}") ? instance_variable_get("@#{name}") : nil }
define_method("#{name}=") do |value|
send("#{name}_will_change!") if self.class <= ActiveModel::Dirty && value != send(name)
instance_variable_set("@#{name}", value)
end
end
def self.create
object = new
object.save
object
end
def initialize(attrs = {})
attrs.each { |attr, value| send("#{attr}=", value) }
end
def attributes
@attributes ||= {}
end
def save
true
end
end
model = Class.new(parent) do
def self.name
'Foo'
end
model_attribute :state
end
model.class_eval(&block) if block_given?
model
end
end