gocardless / statesman

A statesmanlike state machine library.
https://gocardless.com/blog/statesman/
MIT License
1.78k stars 163 forks source link

No easy way to find previous state #348

Open marclerodrigues opened 5 years ago

marclerodrigues commented 5 years ago

Closes #263

Before:

previous_state = project.transitions.where(most_recent: false).last.to_state || project.initial_state

After:

project.last_transition.from_state
dmagliola commented 5 years ago

Could we have a from_state property on the Transition model, which does something like this, instead of adding a column?

def from_state
  transitions.where(id < self.id).last.to_state
end

Basically, i'm trying to avoid adding the redundant column. If the concern here is the performance hit of an extra DB call, rather than the non-obvious code one needs to write to get the "next-to-last" transition, then this obviously doesn't help.

marclerodrigues commented 5 years ago

@dmagliola The point of this PR is getting the previous state without another DB call.

marclerodrigues commented 5 years ago

@danwakefield I'm afraid this would be a breaking change since I'm making that a required value when transitioning.

What do you think about adding the from_state in the metadata? This way we wouldn't need a new column and would also save another DB call.

We could do that as a "workaround" and push it in a minor change and make the from_state column required in future major versions. Let me know your thoughts on this.

dmitry commented 3 years ago

What about initial state? last_transition returns only second and next states.