state-machines-activemodel-0.3.0/0000755000175000017500000000000012621631643017043 5ustar abhijithabhijithstate-machines-activemodel-0.3.0/metadata.yml0000644000175000017500000001426612621631643021357 0ustar abhijithabhijith--- !ruby/object:Gem::Specification name: state_machines-activemodel version: !ruby/object:Gem::Version version: 0.3.0 platform: ruby authors: - Abdelkader Boudih - Aaron Pfeifer autorequire: bindir: bin cert_chain: [] date: 2015-06-18 00:00:00.000000000 Z dependencies: - !ruby/object:Gem::Dependency name: state_machines requirement: !ruby/object:Gem::Requirement requirements: - - ">=" - !ruby/object:Gem::Version version: 0.4.0 type: :runtime prerelease: false version_requirements: !ruby/object:Gem::Requirement requirements: - - ">=" - !ruby/object:Gem::Version version: 0.4.0 - !ruby/object:Gem::Dependency name: activemodel requirement: !ruby/object:Gem::Requirement requirements: - - "~>" - !ruby/object:Gem::Version version: '4.1' type: :runtime prerelease: false version_requirements: !ruby/object:Gem::Requirement requirements: - - "~>" - !ruby/object:Gem::Version version: '4.1' - !ruby/object:Gem::Dependency name: bundler requirement: !ruby/object:Gem::Requirement requirements: - - ">=" - !ruby/object:Gem::Version version: '1.6' type: :development prerelease: false version_requirements: !ruby/object:Gem::Requirement requirements: - - ">=" - !ruby/object:Gem::Version version: '1.6' - !ruby/object:Gem::Dependency name: rake requirement: !ruby/object:Gem::Requirement requirements: - - ">=" - !ruby/object:Gem::Version version: '10' type: :development prerelease: false version_requirements: !ruby/object:Gem::Requirement requirements: - - ">=" - !ruby/object:Gem::Version version: '10' - !ruby/object:Gem::Dependency name: appraisal requirement: !ruby/object:Gem::Requirement requirements: - - ">=" - !ruby/object:Gem::Version version: '1' type: :development prerelease: false version_requirements: !ruby/object:Gem::Requirement requirements: - - ">=" - !ruby/object:Gem::Version version: '1' - !ruby/object:Gem::Dependency name: minitest requirement: !ruby/object:Gem::Requirement requirements: - - "~>" - !ruby/object:Gem::Version version: '5.4' type: :development prerelease: false version_requirements: !ruby/object:Gem::Requirement requirements: - - "~>" - !ruby/object:Gem::Version version: '5.4' - !ruby/object:Gem::Dependency name: minitest-reporters requirement: !ruby/object:Gem::Requirement requirements: - - ">=" - !ruby/object:Gem::Version version: '0' type: :development prerelease: false version_requirements: !ruby/object:Gem::Requirement requirements: - - ">=" - !ruby/object:Gem::Version version: '0' description: Adds support for creating state machines for attributes on ActiveModel email: - terminale@gmail.com - aaron@pluginaweek.org executables: [] extensions: [] extra_rdoc_files: [] files: - ".gitignore" - ".travis.yml" - Appraisals - Gemfile - LICENSE.txt - README.md - Rakefile - gemfiles/active_model_4.1.gemfile - gemfiles/active_model_4.2.gemfile - lib/state_machines-activemodel.rb - lib/state_machines/integrations/active_model.rb - lib/state_machines/integrations/active_model/locale.rb - lib/state_machines/integrations/active_model/version.rb - state_machines-activemodel.gemspec - test/files/en.yml - test/integration_test.rb - test/machine_by_default_test.rb - test/machine_errors_test.rb - test/machine_multiple_test.rb - test/machine_with_callbacks_test.rb - test/machine_with_dirty_attribute_and_custom_attributes_during_loopback_test.rb - test/machine_with_dirty_attribute_and_state_events_test.rb - test/machine_with_dirty_attributes_and_custom_attribute_test.rb - test/machine_with_dirty_attributes_during_loopback_test.rb - test/machine_with_dirty_attributes_test.rb - test/machine_with_dynamic_initial_state_test.rb - test/machine_with_events_test.rb - test/machine_with_failed_after_callbacks_test.rb - test/machine_with_failed_before_callbacks_test.rb - test/machine_with_initialized_state_test.rb - test/machine_with_internationalization_test.rb - test/machine_with_model_state_attribute_test.rb - test/machine_with_non_model_state_attribute_undefined_test.rb - test/machine_with_state_driven_validations_test.rb - test/machine_with_states_test.rb - test/machine_with_static_initial_state_test.rb - test/machine_with_validations_and_custom_attribute_test.rb - test/machine_with_validations_test.rb - test/test_helper.rb homepage: https://github.com/state-machines/state_machines-activemodel licenses: - MIT metadata: {} post_install_message: rdoc_options: [] require_paths: - lib required_ruby_version: !ruby/object:Gem::Requirement requirements: - - ">=" - !ruby/object:Gem::Version version: 1.9.3 required_rubygems_version: !ruby/object:Gem::Requirement requirements: - - ">=" - !ruby/object:Gem::Version version: '0' requirements: [] rubyforge_project: rubygems_version: 2.2.3 signing_key: specification_version: 4 summary: ActiveModel integration for State Machines test_files: - test/files/en.yml - test/integration_test.rb - test/machine_by_default_test.rb - test/machine_errors_test.rb - test/machine_multiple_test.rb - test/machine_with_callbacks_test.rb - test/machine_with_dirty_attribute_and_custom_attributes_during_loopback_test.rb - test/machine_with_dirty_attribute_and_state_events_test.rb - test/machine_with_dirty_attributes_and_custom_attribute_test.rb - test/machine_with_dirty_attributes_during_loopback_test.rb - test/machine_with_dirty_attributes_test.rb - test/machine_with_dynamic_initial_state_test.rb - test/machine_with_events_test.rb - test/machine_with_failed_after_callbacks_test.rb - test/machine_with_failed_before_callbacks_test.rb - test/machine_with_initialized_state_test.rb - test/machine_with_internationalization_test.rb - test/machine_with_model_state_attribute_test.rb - test/machine_with_non_model_state_attribute_undefined_test.rb - test/machine_with_state_driven_validations_test.rb - test/machine_with_states_test.rb - test/machine_with_static_initial_state_test.rb - test/machine_with_validations_and_custom_attribute_test.rb - test/machine_with_validations_test.rb - test/test_helper.rb has_rdoc: state-machines-activemodel-0.3.0/.gitignore0000644000175000017500000000025512621631643021035 0ustar abhijithabhijith*.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.3.0/.travis.yml0000644000175000017500000000034612621631643021157 0ustar abhijithabhijithlanguage: ruby sudo: false cache: bundler rvm: - 2.1 - 2.2 - jruby - rbx-2 gemfile: - gemfiles/active_model_4.1.gemfile - gemfiles/active_model_4.2.gemfile matrix: allow_failures: - rvm: jruby - rvm: rbx-2state-machines-activemodel-0.3.0/test/0000755000175000017500000000000012621631643020022 5ustar abhijithabhijithstate-machines-activemodel-0.3.0/test/files/0000755000175000017500000000000012621631643021124 5ustar abhijithabhijithstate-machines-activemodel-0.3.0/test/files/en.yml0000644000175000017500000000013412621631643022247 0ustar abhijithabhijithen: activemodel: errors: messages: invalid_transition: "cannot %{event}"state-machines-activemodel-0.3.0/test/machine_with_failed_before_callbacks_test.rb0000644000175000017500000000175612621631643030703 0ustar abhijithabhijithrequire_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.3.0/test/machine_with_dirty_attributes_during_loopback_test.rb0000644000175000017500000000252312621631643032752 0ustar abhijithabhijithrequire_relative 'test_helper' class MachineWithDirtyAttributesDuringLoopbackTest < BaseTestCase def setup @model = new_model do include ActiveModel::Dirty define_attribute_methods [:state] 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_equal nil, @record.changes['state'] end end class MachineWithDirtyAttributeAndCustomAttributesDuringLoopbackTest < BaseTestCase def setup @model = new_model do include ActiveModel::Dirty model_attribute :status define_attribute_methods [:status] 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_equal nil, @record.changes['status'] end end state-machines-activemodel-0.3.0/test/machine_with_dirty_attribute_and_state_events_test.rb0000644000175000017500000000113112621631643032745 0ustar abhijithabhijithrequire_relative 'test_helper' class MachineWithDirtyAttributeAndStateEventsTest < BaseTestCase def setup @model = new_model do include ActiveModel::Dirty define_attribute_methods [:state] 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_equal nil, @record.changes['state'] end end state-machines-activemodel-0.3.0/test/machine_multiple_test.rb0000644000175000017500000000102512621631643024723 0ustar abhijithabhijithrequire_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.3.0/test/machine_with_initialized_state_test.rb0000644000175000017500000000165112621631643027635 0ustar abhijithabhijithrequire_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.3.0/test/machine_with_dirty_attributes_test.rb0000644000175000017500000000165612621631643027536 0ustar abhijithabhijithrequire_relative 'test_helper' class MachineWithDirtyAttributesTest < BaseTestCase def setup @model = new_model do include ActiveModel::Dirty define_attribute_methods [:state] 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.3.0/test/machine_with_callbacks_test.rb0000644000175000017500000000632712621631643026054 0ustar abhijithabhijithrequire_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 state-machines-activemodel-0.3.0/test/machine_with_model_state_attribute_test.rb0000644000175000017500000000156112621631643030513 0ustar abhijithabhijithrequire_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.3.0/test/integration_test.rb0000644000175000017500000000160512621631643023733 0ustar abhijithabhijithrequire_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.3.0/test/machine_with_dirty_attributes_and_custom_attribute_test.rb0000644000175000017500000000175312621631643034033 0ustar abhijithabhijithrequire_relative 'test_helper' class MachineWithDirtyAttributesAndCustomAttributeTest < BaseTestCase def setup @model = new_model do include ActiveModel::Dirty model_attribute :status define_attribute_methods [:status] 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.3.0/test/machine_with_states_test.rb0000644000175000017500000000046612621631643025436 0ustar abhijithabhijithrequire_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.3.0/test/machine_with_non_model_state_attribute_undefined_test.rb0000644000175000017500000000124612621631643033406 0ustar abhijithabhijithrequire_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.3.0/test/machine_with_internationalization_test.rb0000644000175000017500000001521712621631643030400 0ustar abhijithabhijithrequire_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_only_add_locale_once_in_load_path assert_equal 1, I18n.load_path.select { |path| path =~ %r{active_model/locale\.rb$} }.length # Create another ActiveModel model that will triger the i18n feature new_model assert_equal 1, I18n.load_path.select { |path| path =~ %r{active_model/locale\.rb$} }.length end def test_should_add_locale_to_beginning_of_load_path @original_load_path = I18n.load_path I18n.backend = I18n::Backend::Simple.new app_locale = File.dirname(__FILE__) + '/files/en.yml' default_locale = File.dirname(__FILE__) + '/../lib/state_machines/integrations/active_model/locale.rb' I18n.load_path = [app_locale] StateMachines::Machine.new(@model) assert_equal [default_locale, app_locale].map { |path| File.expand_path(path) }, I18n.load_path.map { |path| File.expand_path(path) } ensure I18n.load_path = @original_load_path 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.3.0/test/machine_with_failed_after_callbacks_test.rb0000644000175000017500000000171612621631643030536 0ustar abhijithabhijithrequire_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 ././@LongLink0000644000000000000000000000016100000000000011601 Lustar rootrootstate-machines-activemodel-0.3.0/test/machine_with_dirty_attribute_and_custom_attributes_during_loopback_test.rbstate-machines-activemodel-0.3.0/test/machine_with_dirty_attribute_and_custom_attributes_during_loop0000644000175000017500000000132712621631643034770 0ustar abhijithabhijithrequire_relative 'test_helper' class MachineWithDirtyAttributeAndCustomAttributesDuringLoopbackTest < BaseTestCase def setup @model = new_model do include ActiveModel::Dirty model_attribute :status define_attribute_methods [:status] 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_equal nil, @record.changes['status'] end end state-machines-activemodel-0.3.0/test/machine_with_dynamic_initial_state_test.rb0000644000175000017500000000062212621631643030462 0ustar abhijithabhijithrequire_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.3.0/test/machine_with_validations_test.rb0000644000175000017500000000241512621631643026444 0ustar abhijithabhijithrequire_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.3.0/test/machine_with_events_test.rb0000644000175000017500000000046012621631643025431 0ustar abhijithabhijithrequire_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.3.0/test/machine_by_default_test.rb0000644000175000017500000000107612621631643025214 0ustar abhijithabhijithrequire_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.3.0/test/machine_errors_test.rb0000644000175000017500000000114512621631643024407 0ustar abhijithabhijithrequire_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.3.0/test/machine_with_validations_and_custom_attribute_test.rb0000644000175000017500000000106112621631643032737 0ustar abhijithabhijithrequire_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.3.0/test/test_helper.rb0000644000175000017500000000255712621631643022676 0ustar abhijithabhijithbegin 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) } @changed_attributes = {} end def attributes @attributes ||= {} end def save @changed_attributes = {} 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 state-machines-activemodel-0.3.0/test/machine_with_static_initial_state_test.rb0000644000175000017500000000054112621631643030325 0ustar abhijithabhijithrequire_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.3.0/test/machine_with_state_driven_validations_test.rb0000644000175000017500000000155212621631643031214 0ustar abhijithabhijithrequire_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.3.0/gemfiles/0000755000175000017500000000000012621631643020636 5ustar abhijithabhijithstate-machines-activemodel-0.3.0/gemfiles/active_model_4.1.gemfile0000644000175000017500000000033212621631643025203 0ustar abhijithabhijith# This file was generated by Appraisal source "https://rubygems.org" gem "activemodel", :github => "rails/rails", :branch => "4-2-stable" platforms :mri_20, :mri_21 do gem "pry-byebug" end gemspec :path => "../" state-machines-activemodel-0.3.0/gemfiles/active_model_4.2.gemfile0000644000175000017500000000033212621631643025204 0ustar abhijithabhijith# This file was generated by Appraisal source "https://rubygems.org" gem "activemodel", :github => "rails/rails", :branch => "4-2-stable" platforms :mri_20, :mri_21 do gem "pry-byebug" end gemspec :path => "../" state-machines-activemodel-0.3.0/state_machines-activemodel.gemspec0000644000175000017500000000241712621631643025675 0ustar abhijithabhijith# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require '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 = `git ls-files -z`.split("\x0") spec.test_files = spec.files.grep(/^test\//) spec.require_paths = ['lib'] spec.required_ruby_version = '>= 1.9.3' spec.add_dependency 'state_machines', '>= 0.4.0' spec.add_dependency 'activemodel', '~> 4.1' 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.3.0/Gemfile0000644000175000017500000000024512621631643020337 0ustar abhijithabhijithsource 'https://rubygems.org' # Specify your gem's dependencies in state_machine2_activemodel.gemspec gemspec platforms :mri_20, :mri_21 do gem 'pry-byebug' end state-machines-activemodel-0.3.0/Rakefile0000644000175000017500000000026312621631643020511 0ustar abhijithabhijithrequire '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.3.0/lib/0000755000175000017500000000000012621631643017611 5ustar abhijithabhijithstate-machines-activemodel-0.3.0/lib/state_machines-activemodel.rb0000644000175000017500000000006312621631643025416 0ustar abhijithabhijithrequire 'state_machines/integrations/active_model' state-machines-activemodel-0.3.0/lib/state_machines/0000755000175000017500000000000012621631643022600 5ustar abhijithabhijithstate-machines-activemodel-0.3.0/lib/state_machines/integrations/0000755000175000017500000000000012621631643025306 5ustar abhijithabhijithstate-machines-activemodel-0.3.0/lib/state_machines/integrations/active_model/0000755000175000017500000000000012621631643027741 5ustar abhijithabhijithstate-machines-activemodel-0.3.0/lib/state_machines/integrations/active_model/locale.rb0000644000175000017500000000053212621631643031525 0ustar abhijithabhijith{ 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.3.0/lib/state_machines/integrations/active_model/version.rb0000644000175000017500000000015412621631643031753 0ustar abhijithabhijithmodule StateMachines module Integrations module ActiveModel VERSION = '0.3.0' end end end state-machines-activemodel-0.3.0/lib/state_machines/integrations/active_model.rb0000644000175000017500000004613412621631643030276 0ustar abhijithabhijithrequire '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. 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 %w(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.merge(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 = {}) 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 # Initializes class-level extensions and defaults for this machine def after_initialize super() load_locale end # Loads any locale files needed for translating validation errors def load_locale I18n.load_path.unshift(locale_path) unless I18n.load_path.include?(locale_path) end def locale_path "#{File.dirname(__FILE__)}/active_model/locale.rb" 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.3.0/Appraisals0000644000175000017500000000035012621631643021063 0ustar abhijithabhijith# ActiveModel integrations appraise 'active_model_4.1' do gem 'activemodel', github: 'rails/rails', branch: '4-2-stable' end appraise 'active_model_4.2' do gem 'activemodel', github: 'rails/rails', branch: '4-2-stable' end state-machines-activemodel-0.3.0/README.md0000644000175000017500000000442112621631643020323 0ustar abhijithabhijith[![Build Status](https://travis-ci.org/state-machines/state_machines-activemodel.svg?branch=master)](https://travis-ci.org/state-machines/state_machines-activemodel) [![Code Climate](https://codeclimate.com/github/state-machines/state_machines-activemodel.png)](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 ## 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 ``` Dependencies Active Model 4.1+ ## 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.3.0/LICENSE.txt0000644000175000017500000000213512621631643020667 0ustar abhijithabhijithCopyright (c) 2006-2012 Aaron Pfeifer Copyright (c) 2014-2015 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.