Giter Site home page Giter Site logo

state-machines / state_machines-activerecord Goto Github PK

View Code? Open in Web Editor NEW
391.0 391.0 85.0 130 KB

StateMachines Active Record Integration

Home Page: https://github.com/state-machines/state_machines-activerecord

License: MIT License

Ruby 100.00%
activerecord ruby state-machine

state_machines-activerecord's People

Contributors

carlesjove avatar casaper avatar casperisfine avatar diegotoral avatar dmytrostepaniuk avatar duleorlovic avatar edouard-chin avatar hishammalik avatar huoxito avatar jhawthorn avatar kaanozkan avatar lbrito1 avatar lulalala avatar mbobin avatar olivierlacan avatar olleolleolle avatar rafaelfranca avatar rosskevin avatar seuros avatar simi avatar tomash avatar twalpole avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

state_machines-activerecord's Issues

accessing AR attributes

how do i implement such a case:

ticket with state in_progress receives transition finish. if ticket got reviewer_id, it should change state to review or complete if there is no reviewer... i tried to do this:

      event :finish do 
        if reviewer
          transition in_progress: :review
        else
          transition in_progress: :complete
        end
      end

but it throws an error about there's no such a method for StateMachines

i tried to put this var into initialize block with no luck

Scopes are not being created in activerecord 4.1.9 from a rails engine

When debugging scope creation, it appears that the #define_helper method is never called.

Here's the snippet from the link above:

    def define_scopes(custom_plural = nil)
      plural = custom_plural || pluralize(name)

      [:with, :without].each do |kind|
        [name, plural].map { |s| s.to_s }.uniq.each do |suffix|
          method = "#{kind}_#{suffix}"

          if scope = send("create_#{kind}_scope", method)
            # Converts state names to their corresponding values so that they
            # can be looked up properly
            define_helper(:class, method) do |machine, klass, *states|
              run_scope(scope, machine, klass, states)
            end
          end
        end
      end
    end

The send in debug mode equates to:

scope = send("create_without_scope", 'without_states')

This hits the no-op #create_without_scope.

How is the StateMachines::Integrations::ActiveRecord#create_without_scope intended to be wired in to override the same method in machines.rb?

Observers aren't working

I replaced my existing statemachine gem with this one so I could move up to Rails 4.2 and found that my observers aren't getting triggered.

Did that code get left behind? The documentation suggests that it should work with observers, but that's just been copied across from the old state_machine gem.

Where do I need to look in the code to fix this?

Default transition action

Hi!
Is it intended not to set save as the default action in a transition or is something you are considering to add in the future?

assigning state_event overrides the state no matter what in Rails 4.2

This might be a related issue: pluginaweek/state_machine#327
Here I have a Car class:

class Car < ActiveRecord::Base
  attr_accessible :state_event

  state_machine :state, initial: :parked do
    event :drive do
      transition :parked => :driving
    end
    event :stop do
      transition :driving => :parked
    end
    event :turn_right do
      transition :driving => :moving_right 
    end
  end

end
c = Car.create!
c.update_attributes({ state_event: :turn_right })

The last command will successfully save the car and update the state attribute to :turn_right, even though it should fail and return false, since a car cannot move from it's initial :parked state to :moving_right.
If I run:

c.state = :moving_right
c.save!

I will get the false value properly returned.

Model callbacks triggering twice when calling a transition

after_save :model_callback

...

state_machine :state, initial: :inactive do
  state :inactive, value: :inactive
  state :active, value: :active
  event :activate do
      transition inactive: :active
  end
end

def model_callback
  send_confirmation_instructions if state_changed? && active?
end
# calling transition
my_model.activate

two activation emails are being sent, because callbacks are triggering twice.
I checked this with debugger (pry)

Undefined method `state' for #<Post not initialized> error

Been trying to make spree run with this project and noticed that every time I point the Gemfile to git or the gem release I get an error like this Undefined method 'state' for #<Post not initialized> (tested on a bran new rails project as well). Whenever I point to the code using path (local code) it works fine though. Have you experienced anything similar? (I might have something wrong in my local bundle config or set up and I can't see it right now)

For some reason the activerecord object is being initialized using the Machine#initialize method rather than the ActiveRecord#initialize.

To reproduce put a state machine on an activerecord object, e.g.:

class Post < ActiveRecord::Base
  state_machine initial: :draft do
    event :review do
      transition to: :reviwed, from: :draft
    end

    event :complete do
      transition to: :completed
    end
  end
end

Open rails c and then Post.new.

Full stack trace of the error:

NoMethodError: undefined method `state' for #<Post not initialized>
        from /Users/huoxito/.gem/ruby/2.1.3/gems/activemodel-4.2.0/lib/active_model/attribute_methods.rb:433:in `method_missing'
        from /Users/huoxito/.gem/ruby/2.1.3/gems/state_machines-0.1.0/lib/state_machines/machine.rb:1053:in `read'
        from /Users/huoxito/.gem/ruby/2.1.3/gems/state_machines-0.1.0/lib/state_machines/machine.rb:1904:in `initialize_state?'
        from /Users/huoxito/.gem/ruby/2.1.3/bundler/gems/state_machines-activerecord-041af9e52445/lib/state_machines/integrations/active_record.rb:573:in `initialize_state'
        from /Users/huoxito/.gem/ruby/2.1.3/gems/state_machines-0.1.0/lib/state_machines/machine_collection.rb:29:in `block in initialize_states'
        from /Users/huoxito/.gem/ruby/2.1.3/gems/state_machines-0.1.0/lib/state_machines/machine_collection.rb:28:in `each_value'
        from /Users/huoxito/.gem/ruby/2.1.3/gems/state_machines-0.1.0/lib/state_machines/machine_collection.rb:28:in `initialize_states'
        from /Users/huoxito/.gem/ruby/2.1.3/gems/state_machines-0.1.0/lib/state_machines/machine.rb:1925:in `initialize'
        from /Users/huoxito/.gem/ruby/2.1.3/gems/activerecord-4.2.0/lib/active_record/inheritance.rb:61:in `new'
        from /Users/huoxito/.gem/ruby/2.1.3/gems/activerecord-4.2.0/lib/active_record/inheritance.rb:61:in `new'
        from (irb):1
        from /Users/huoxito/.gem/ruby/2.1.3/gems/railties-4.2.0/lib/rails/commands/console.rb:110:in `start'
        from /Users/huoxito/.gem/ruby/2.1.3/gems/railties-4.2.0/lib/rails/commands/console.rb:9:in `start'
        from /Users/huoxito/.gem/ruby/2.1.3/gems/railties-4.2.0/lib/rails/commands/commands_tasks.rb:68:in `console'
        from /Users/huoxito/.gem/ruby/2.1.3/gems/railties-4.2.0/lib/rails/commands/commands_tasks.rb:39:in `run_command!'
        from /Users/huoxito/.gem/ruby/2.1.3/gems/railties-4.2.0/lib/rails/commands.rb:17:in `<top (required)>'
        from bin/rails:8:in `require'
        from bin/rails:8:in `<main>'irb(main):002:0>

use_transactions: false not respected in execution

I should note that I am debugging this in a before_transition.

I'm not sure what is going on yet, but I can see that the machine.rb#within_transaction is not run (which seems to evaluate this flag). With the active record integration, it runs the transaction every time. I'm not sure if it is overwriting that check in machine or what is occuring, but I cannot seem to turn off transactions as this code is always run:

      # Runs a new database transaction, rolling back any changes by raising
      # an ActiveRecord::Rollback exception if the yielded block fails
      # (i.e. returns false).
      def transaction(object)
        result = nil
        object.class.transaction do
          raise ::ActiveRecord::Rollback unless result = yield
        end
        result
      end

The state_machine is configured with:

    state_machine :state, initial: :uninitialized, use_transactions: false do

All state validations firing during initial state

Model:

class Recipe < ApplicationRecord
  include Redis::Objects
  include FriendlyId

  Gutentag::ActiveRecord.call self

  belongs_to :author, class_name: "Account"
  belongs_to :approver, class_name: "Account"
  belongs_to :publisher, class_name: "Account"
  belongs_to :denier, class_name: "Account"
  belongs_to :remover, class_name: "Account"

  validates_presence_of :slug
  validates_presence_of :ingredients
  validates_length_of :ingredients, minimum: 1
  validates_presence_of :author
  validates_presence_of :created_at
  validates_presence_of :updated_at

  before_create do
    self.author = current_account
  end

  attr_accessor :current_account

  friendly_id :name, :use => [:slugged, :history]

  value :queued_at, marshal: true
  value :published_at, marshal: true
  value :removed_at, marshal: true

  state_machine :state, initial: :draft do
    event :publish do
      transition :draft => :queued
    end

    event :publish do
      transition :draft => :published, if: :allowed_to_autopublish?
    end

    event :remove do
      transition :published => :draft, if: :allowed_to_remove?
    end

    event :deny do
      transition :queued => :draft, if: :allowed_to_deny?
    end

    event :approve do
      transition :queued => :published, if: :allowed_to_approve?
    end

    before_transition any => :queued do |record|
      record.queued_at = Time.zone.now
    end

    before_transition any => :published do |record|
      record.published_at = Time.zone.now
    end

    before_transition any => :removed do |record|
      record.removed_at = Time.zone.now
    end

    state :queued do
      validates_presence_of :queued_at
    end

    state :removed do
      validates_presence_of :removed_at
      validates_presence_of :remover
    end

    state :published do
      validates_presence_of :published_at
      validates_presence_of :publisher
    end
  end

  private def allowed_to_autopublish?
    current_account.verified? || current_account.moderator?
  end

  private def allowed_to_deny?
    current_account.administrator? || current_account.moderator?
  end

  private def allowed_to_approve?
    current_account.administrator? || current_account.moderator?
  end

  private def allowed_to_remove?
    current_account.administrator? || current_account.moderator?
  end
end

Resource:

[2] pry(#<Admin::RecipesController>)> resource.save!
ActiveRecord::RecordInvalid: Validation failed: Approver must exist, Publisher must exist, Denier must exist, Remover must exist, Ingredients can't be blank, Ingredients is too short (minimum is 1 character), Created at can't be blank, Updated at can't be blank

defining associations in state block break

I want a relation to only be available to the model when in a certain state:

state_machine :initial do
  state :finished do
    has_many :clubs
  end
...

This doesn't work however, with the following error:

ArgumentError:
  Unknown key: :if. Valid keys are: :class_name, :anonymous_class, :foreign_key, :validate, :autosave, :table_name, :before_add, :after_add, :before_remove, :after_remove, :extend, :primary_key, :dependent, :as, :through, :source, :source_type, :inverse_of, :counter_cache, :join_table, :foreign_type, :index_errors
# /usr/local/bundle/gems/state_machines-0.4.0/lib/state_machines/assertions.rb:18:in `block in assert_valid_keys'
# /usr/local/bundle/gems/state_machines-0.4.0/lib/state_machines/assertions.rb:16:in `each_key'
# /usr/local/bundle/gems/state_machines-0.4.0/lib/state_machines/assertions.rb:16:in `assert_valid_keys'
# /usr/local/bundle/gems/activerecord-5.0.7.1/lib/active_record/associations/builder/association.rb:78:in `validate_options'
# /usr/local/bundle/gems/activerecord-5.0.7.1/lib/active_record/associations/builder/association.rb:44:in `create_reflection'
# /usr/local/bundle/gems/activerecord-5.0.7.1/lib/active_record/associations/builder/association.rb:29:in `build'
# /usr/local/bundle/gems/activerecord-5.0.7.1/lib/active_record/associations.rb:1371:in `has_many'
# /usr/local/bundle/gems/state_machines-0.4.0/lib/state_machines/state_context.rb:130:in `method_missing'
# ./app/models/owner/base.rb:26:in `block (2 levels) in <class:Base>
...

The if error, however, doesn't come from my code, as shown above, but from the state_machine code, which introduces an if condition before calling rails's has_many.

I'm using rails 5.0, btw.

Transition specs fails when switching to state_machines-activerecord

I started with state_machines, and wrote a few specs about my workflow with state_machines-rspec.

When I decided later to switch to state_machines-activerecord, my transition specs failed, and I can't see why. That kind of spec:

it { is_expected.to transition_from :idle, to_state: :received, on_event: :receive }

generates that kind of error:

Failure/Error:
    is_expected.to transition_from :idle, to_state: :received,
                                             on_event: :receive

Expected to be able to transition state from: idle to: received, on_event: receive

which is weird, considering I have this code in my model:

event :receive do
    transition idle: :received
end

Is there something I should know about the config of the rspec gem?

(I'm building a Rails 5.1 app)

get value for state name?

I have a bunch of states defined with custom values. How can I retrieve the value for a given state? Thanks!

Accessing scopes

I've switched my Rails 4.1 project from the unmaintained state_machine gem to this one without making any other code changes. I have a model in my application called Order. It's initial state is 'submitted'. Upon calling the following:

Order.submitted

I'm getting the following error:

NoMethodError: undefined methodcall' for #Order::ActiveRecord_Relation:0x007ff6b39b8168`

In general, this error appears to be related to this:
http://stackoverflow.com/questions/26413500/undefined-method-call-for-activerecordrelation

But I glanced over the code in this gem, and it appears that the scopes are being defined properly?

after_transition's and before_transition's `do` only executes a single method or first array entry

If you want to call multiple methods before or after a transaction and specify an array as a key for the do: entry, for example...

after_transition on: :event, do: [:foo, :bar]
before_transition on: :event, do: [:foo, :bar]

...foo will be executed, but bar will not. This does not seem to be th case with an array passed to the on: entry, for example...

after_transition on: [:event1, :event2], do: :foo
before_transition on: [:event1, :event2], do: :foo

...foo will be called in both cases.

Rubygem release?

Now that the state_machines gem has been updated to 0.3.0, any chance for a new release of state_machines-activerecord also?

Default translations not used

The docs for this gem say that default :en translations are set, but apparently they are not used in Rails 4.2.1. In a freshly generated Rails project with this gem added, inside a rails console:

irb(main):003:0> I18n.t!('activerecord.errors.messages.invalid_transition')
I18n::MissingTranslationData: translation missing: en.activerecord.errors.messages.invalid_transition

Callbacks pass when they add errors but don't return false - is this desired behaviour?

Between state machine 1.1 and 1.2, the behaviour of callbacks on ActiveRecord objects was changed. This behaviour has been carried over into the state_machines gem.

Given the following class:

class Vehicle < ActiveRecord::Base
  state_machine :state, initial: :parked do
    event :drive do
      transition :parked => :driving
    end

    before_transition to: :driving, do: :validate_car_can_drive
  end

  def validate_car_can_drive
    errors.add(:base, "Your car is broken.") if broken?
  end

  private

  def broken?
    false
  end
end

These tests pass in state_machine 1.1, but fail in state_machines and state_machine 1.2:

context "with a failing callback" do
  let(:vehicle) { Vehicle.create }

  before(:each) do
    allow(vehicle).to receive(:broken?).and_return(true)
  end

  it "does not update the state" do
    expect { vehicle.drive! rescue nil }.not_to change(vehicle, :state)
  end

  it "raises an error" do
    expect { vehicle.drive! }.to raise_error(StateMachine::InvalidTransition)
  end
end

No error is raised, and the state is changed.

Changing the callback fixes these failures, and is backward compatible.

def validate_car_can_drive
  if broken?
    errors.add(:base, "Your car is broken.")
    false
  end
end

Is this the desired behaviour?

with_state on associated Model

I have a model, say Product, with a belongs_to relation to Manufacturer. The Manufacturer Model has a state machine, and now

Manufacturer.with_state(:new)

works, but

product.manufacturer.with_state(:new)

gives NoMethodError: undefined methodwith_state'`

For a has_many association I get undefined methodwith_state' for #<ActiveRecord::AssociationRelation []`

Note: This worked with the discontinued state_machine gem v.1.2.0

Implicit even triggers do not work inside of callbacks

I'm on Rails 4.1.1 and the following behavior seems a bit odd and I'm wondering if its a limitation in the way transitions are done, or possibly a bug(I may also be doing something wrong here)

My Model

class Event < ActiveRecord::Base

    before_validation :transition_status, :on => :update

    def transition_status
      self.status_event = :was_updated
    end

    state_machine :status, :initial => :new do
      event :pend do
        transition [:new, :confirmed] => :pending, :unless => :start_date_passed?
      end
      event :was_updated do
        transition [:new, :pending, :confirmed] => :pending
      end
      event :confirm do
        transition :pending => :confirmed
      end
   end
end

Now some sample code:

@event = Event.first
@event.confirmed? # => true
@event.update_attribute(:start_date => @event.start_date + 1.day)
@event.reload.status # => confirmed
@event.confirmed? # => true

note Assigning using @event.start_date and then using #save has the same effect

I expected this to change the status back to pending, but it never seems to apply the transition when its called(or assigned) in the callback.

My only thought here is that the #around_save documented here "prevents" the before_transition from being called and therefore the implicit state change never runs. This is partially supported by the evidence here

At the bottom of this section in the main state machine docs, they say
See each integration's API documentation for more information on the implicit approach.

Searching the entire repo here yields no results for implicit. I'd be glad to submit a PR with some updated info after I've cleared up my current issue.

Doesn't seem to respect conditional validations

I have a model with a conditional validation

validates :nda_accepted,
  presence: true,
  unless: :draft?

but if I try to transition it fails.

>> Rfq.last.valid?
=> true
>> Rfq.last.delete_draft!
StateMachines::InvalidTransition: Cannot transition state via :delete_draft from :draft (Reason(s): Nda accepted can't be blank)
from /Users/mmoen/code/UnderpantsGnome/britehub-app/vendor/bundle/ruby/2.2.0/gems/state_machines-0.4.0/lib/state_machines/event.rb:224:in `block in add_actions'

Gems

gem 'state_machines', '~> 0.4.0'
gem 'state_machines-activerecord', '~> 0.3.0'
gem 'state_machines-activemodel', '~> 0.3.0'

Autosaving a record fails on Rails 4.2

Simple model looks like this (has status:string column)

class Event < ActiveRecord::Base

  state_machine :status, initial: :open do
    event :submit do
      transition [:open, :rejected] => :submitted
    end

    event :approve do
      transition submitted: :approved
    end

    event :reject do
      transition submitted: :rejected
    end
  end
end

Trying to change a state, expecting database update

Entry.new.submit
=> true

But nothing gets updated.

state_machines-activerecord 0.5.1 breaks attribute default with procs

It appears that state_machines-activerecord 0.5.1 breaks defining attributes with default value determined by proc.

In 0.5.0, the proc would be evaluated at the instantiation of each object. With state_machines-activerecord 0.5.1, it appears the that proc is evaluated once at class definition time and the value is reused for all objects of that class

Given (in Rails 5.1.6):

class Clip < ApplicationRecord
  attribute :uuid, :string, default: -> { SecureRandom.uuid }
end

With state_machines-activerecord 0.5.0:

[1] pry(main)> c1 = Clip.new
=> #<Clip:0x00007ff5e2a720d0
 id: nil,
 uuid: "0901871e-0d04-409b-b248-7332ce4ad768">
[2] pry(main)> c2 = Clip.new
=> #<Clip:0x00007ff5e1f36360
 id: nil,
 uuid: "3d130d07-605d-44ea-81a8-3e8991fc4761">

With state_machines-activerecord 0.5.1:

[1] pry(main)> c1 = Clip.new
=> #<Clip:0x00007ff053c98100
 id: nil,
 uuid: "6d4f5d5e-0ed1-4fd8-99a7-5ca0dd89fd9d">
[2] pry(main)> c2 = Clip.new
=> #<Clip:0x00007ff05441c930
 id: nil,
 uuid: "6d4f5d5e-0ed1-4fd8-99a7-5ca0dd89fd9d">

Scope doesn't select records with NULL state

class Product < ActiveRecord::Base

  state_machine do
    event :delete do
      transition any - :deleted => :deleted
    end
  end
end

Running Product.without_state(:deleted) produces:
SELECT "products".* FROM "products" WHERE ("products"."state" NOT IN ('deleted'))

This doesn't select records with NULL state. Using IS DISTINCT FROM 'deleted' in Postgres selects all values not equal to deleted including NULLs.

Using v0.5.1 and Postgres 9.6

Parameter to transition

Hi,

I would love to see the ability to give parameters to transitions, something like:

    state_machine :state, initial: :new do
      transition :new => :processing, on: :start_processing
      transition :processing => :processed, on: :processing_completed
      transition :processing => :error, on: :processing_failed do |obj, transition, params|
        obj.update_parameters(error => params.first)
      end
    end
....
   my_obj.start_processing!

   begin
     ....
    rescue StandardError => e
       my_obj.processing_failed(e.message)
    end

multiple machines per model ?

Greetings,

I'm looking for an implementation that supports multiple fsm.

The originating project advertised multiple state machines per object - the current docs don't explicitly say this is the case.

thanks.
Jodi

state_machines-activerecord has problems with minitest

When I try to run tests using minitest, I get this hard failure that I cannot recover from:

/Users/jon/.rvm/gems/ruby-2.2.3/gems/bundler-1.11.2/lib/bundler/runtime.rb:80:in `rescue in block (2 levels) in require': There was an error while trying to load the gem 'state_machines-activerecord'. (Bundler::GemRequireError)
    from /Users/jon/.rvm/gems/ruby-2.2.3/gems/bundler-1.11.2/lib/bundler/runtime.rb:76:in `block (2 levels) in require'
    from /Users/jon/.rvm/gems/ruby-2.2.3/gems/bundler-1.11.2/lib/bundler/runtime.rb:72:in `each'
    from /Users/jon/.rvm/gems/ruby-2.2.3/gems/bundler-1.11.2/lib/bundler/runtime.rb:72:in `block in require'
    from /Users/jon/.rvm/gems/ruby-2.2.3/gems/bundler-1.11.2/lib/bundler/runtime.rb:61:in `each'
    from /Users/jon/.rvm/gems/ruby-2.2.3/gems/bundler-1.11.2/lib/bundler/runtime.rb:61:in `require'
    from /Users/jon/.rvm/gems/ruby-2.2.3/gems/bundler-1.11.2/lib/bundler.rb:99:in `require'
    from /Users/jon/Checkr/checkr/spec/spec_helper.rb:4:in `<top (required)>'
    from spec/lib/redis_lock_spec.rb:1:in `require_relative'
    from spec/lib/redis_lock_spec.rb:1:in `<top (required)>'
    from /Users/jon/.rvm/gems/ruby-2.2.3/gems/m-1.3.4/lib/m/executor.rb:78:in `load'
    from /Users/jon/.rvm/gems/ruby-2.2.3/gems/m-1.3.4/lib/m/executor.rb:78:in `suites'
    from /Users/jon/.rvm/gems/ruby-2.2.3/gems/m-1.3.4/lib/m/executor.rb:61:in `tests'
    from /Users/jon/.rvm/gems/ruby-2.2.3/gems/m-1.3.4/lib/m/executor.rb:15:in `execute'
    from /Users/jon/.rvm/gems/ruby-2.2.3/gems/m-1.3.4/lib/m/runner.rb:17:in `run'
    from /Users/jon/.rvm/gems/ruby-2.2.3/gems/m-1.3.4/lib/m.rb:13:in `run'
    from /Users/jon/.rvm/gems/ruby-2.2.3/gems/m-1.3.4/bin/m:4:in `<top (required)>'
    from /Users/jon/.rvm/gems/ruby-2.2.3/bin/m:23:in `load'
    from /Users/jon/.rvm/gems/ruby-2.2.3/bin/m:23:in `<main>'
    from /Users/jon/.rvm/gems/ruby-2.2.3/bin/ruby_executable_hooks:15:in `eval'
    from /Users/jon/.rvm/gems/ruby-2.2.3/bin/ruby_executable_hooks:15:in `<main>'

I am able to run tests fine using ruby directly, but not when using minitest.

super() in initialize throws error

Hi,
using ruby-2.2.2, rails 4.1.16.

When i try to call super() in the initialize method i am getting the following error:

ArgumentError:
wrong number of arguments (1 for 0)

Below is the code:

class DefaultWorkflow
  include ActiveModel::Dirty
  include ActiveModel::Validations
  attr_accessor :state, :workflow_type, :workflow_name, :ticket
  define_attribute_methods [:state]

  def initialize(state = nil, ticket = nil)
    @ticket = ticket
    super()
  end

   state_machine :initial => :open do

    event :start_progress do
      transition [:open, :rework] => :in_progress
    end
  end
end

Wrong arity for initialize

Just came across an issue when upgrading an app from rails 4.2 to rails 5.0.

ActiveRecord::Base has an arity of 2 but the new method defined in define_state_initializer only has an arity of 1. An error is thrown when super is called from a descendent that uses the options argument a

ArgumentError "wrong number of arguments (given 2, expected 0..1)"

is thrown.

Thanks

Rspec support

How do you test this with rspec. can't find any doc.

enum support

In an existing model, my state column is a Rails enum and using state_machine on this column generates some warnings (and probably does not work) :

Instance method "processing?" is already defined in #<Module:0x00000007615c68>, use generic helper instead or set StateMachines::Machine.ignore_method_conflicts = true.
Both Enrollment and its :state machine have defined a different default for "state". Use only one or the other for defining defaults to avoid unexpected behaviors.

I am migrating from aasm and this is a nice feature I miss.

0.4.0 release?

Will 0.4.0 stable be released to RubyGems any time soon? Would be nice for Rails 5 support.

Rails 4.0 support?

Hello,

Quick question: Do the gem authors know if this gem will work with Rails 4.0? Is there a reason AR 4.1 is the lowest AR version?

I'm currently supporting a Rails 4.0 application, and I don't want to upgrade the application to Rails 4.1 just to try out this gem. I'd rather see if this gem could work with Rails 4.0 first. Its also a bummer that the old state_machine gem doesn't support Rails 4.0 and this gem starts at 4.1. Seems like a blind spot to me.

Callbacks for Implicit Event Transitions

Hi! I've noticed that callbacks for implicit event transitions don't work.
Example:

state_machine :state, initial: :profile_details do      
event :pending do
  transition from: all - [:pending, :approved, :rejected], to: :pending
end

after_transition on: :pending, do: :generate_something

and now

profile.pending
profile.reload.something != nil # => true

but

profile.state = 'pending'
profile.save
profile.reload.something # => nil

Is there any solution to enable callbacks using normal assignment of the data (without using events)?

Gems:
Rails 5.0
state_machines-activerecord 0.4.0

Pick initial state from DB schema

In db/schema.rb:

    t.string   "state",             default: "active", null: false

I would expect that: Foo.new.state to be active. But without setting initial: :active in the state machine definition, it sets the value to nil.

edit: using v0.5.1

Around save bug: record saved twice

Hi all,

In Spree I have enabled transactions for the order state machine. Now with inventory units, whenever one is saved, the around_save block gets called and saves it again. It is quite strange, but I end up with 2 inventory_units with I only needed one. Have any of you seen anything similar?

scope used on search application

I have a controller that performs a search. To do that I have a lot of scopes chained together to obtain the right result. Because the user doesn't need to fill all scopes, when a scope is not used, the scope must be transparent.
Usually, I do for example scope :in_range, ->(min, max) { where(id: (min..max)) if min.present? && max.present? }
used like that:

Project.in_range(params[:min], params[:max)
           .in_country(params[:country])
           .with_job(params.dig(:job, :name), params.dig(:job, :user))

what do you think if I modify

def create_scope(name, scope)
lambda { |model, values| model.where(scope.call(values)) }
end
to

        def create_scope(name, scope)
          lambda { |model, values| model.where(scope.call(values)) if values.present? }
        end

So I will change the behaviour from:

$> Project.with_states(nil).to_sql
IndexError: nil is an invalid name

to:

$> Project.with_states(nil).to_sql
=> "SELECT \"projects\".* FROM \"projects\""

scopes not referencing aliased table names

say if I have the following associations

class User < ApplicationRecord
  has_many :active_projects, -> { with_state(:active) }, class_name: Project
end

class Project < ApplicationRecord
  belongs_to :user

  state_machine :state, initial: :pending do
    state :active
  end
end

And if I do the following query

> Project.joins(user: :active_projects).to_sql
=> "SELECT `projects`.* FROM `projects` INNER JOIN `users` ON `users`.`id` = `projects`.`user_id` INNER JOIN `projects` `active_projects_users` ON `active_projects_users`.`user_id` = `users`.`id` AND (`projects`.`state` IN ('active'))"

After trigger event

I'm getting this warning after trigger an state machine event:

DEPRECATION WARNING: `serialized_attributes` is deprecated without replacement, and will be removed in Rails 5.0.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.