I'm currently working on a class, which is basically doing following:
- model gets created
- fetches data (event "get_things!")
- if exception happens, state should become "failed"
- if success, state should be "finished"
I try to implement it as following:
class Fetcher < ActiveRecord::Base
include AASM
aasm do
state :created, initial: true
state :success, :failed
event :succeed do
transitions from: :created, to: :success
end
event :fail do
transitions from: :created, to: :failed
end
end
def read_things(throw_exception = false)
begin
raise RuntimeError.new("RAISED EXCEPTION") if throw_exception
self.content = open("http://ift.tt/2qVwIFK").read
self.succeed!
rescue => e
self.fail!
end
end
end
a = Fetcher.new
a.fetch!(throw_exception = true)
a = Fetcher.new
a.fetch!(throw_exception = false)
It works, but looks somehow not really good to do...
I would prefer something like the error handling which is mentioned in the readme
event :read_things do
before do
self.content = open("http://ift.tt/2qVwIFK").read
self.succeed!
end
error do |e|
self.fail!
end
transitions :from => :created, :to => :success
end
but I dont know if this is really the best practice here?
Any thoughts? Thanks!
Aucun commentaire:
Enregistrer un commentaire