Last active
August 11, 2016 12:50
-
-
Save spieker/a01966e2dd586b47b04f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class BadRequest < StandardError | |
end |
Saving the state is also saving the model, isn't it?
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
You should probably run super at the end of
save!
method, otherwise you're going to ignore other changes.