Skip to content

Instantly share code, notes, and snippets.

@spieker
Last active August 11, 2016 12:50
Show Gist options
  • Save spieker/a01966e2dd586b47b04f to your computer and use it in GitHub Desktop.
Save spieker/a01966e2dd586b47b04f to your computer and use it in GitHub Desktop.
module Concerns
module AasmStateEvent
extend ActiveSupport::Concern
included do
attr_accessor :state_event
end
# It behaves just like `save!`, but when `state_event` was set through
# `assign_attributes` before, `save!` uses the given state with a `!` to
# persist the record.
#
# Example
# =======
#
# ```ruby
# record.assign_attributes state_event: 'start_engine'
# record.save! # => actually calles record.start_engine!
# ```
#
def save!
return super if state_event.blank?
fail BadRequest.new, 'Event not defined' unless known_state_event?
send :"#{state_event}!"
end
def known_state_event?
aasm.events.map.include? state_event.to_s.to_sym
end
end
end
class BadRequest < StandardError
end
@krukgit
Copy link

krukgit commented May 25, 2015

You should probably run super at the end of save! method, otherwise you're going to ignore other changes.

@spieker
Copy link
Author

spieker commented May 27, 2015

Saving the state is also saving the model, isn't it?

@spieker
Copy link
Author

spieker commented May 27, 2015

I have just checked the code, you are right. I'll change the code then when I have tested it. It will then look like this

    def save!
      return super if state_event.blank?
      fail BadRequest.new, 'Event not defined' unless known_state_event?
      send :"#{state_event}"
      super
    end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment