ruby on rails - Transition after a certain period of time in state machine -


i developing rails app , using state_machine gem guide customer through complex process.

at multiple states of process, need trigger events after period time. instance, if customer hasn't confirmed received order after 5 days i'd automatically send him email , enter in parcel tracking process.

class order < activerecord::base        state_machine :initial => :confirmed          after_transition :on => :not_received_by_5_days, |order, transition|             order.send_email             order. .....             order. .....          event :customer_confirmation             transition :confirmed => :order_received         end          event :not_received_by_5_days             transition :confirmed => :parcel_tracking_process         end          def send_email             blabla         end     end  end 

editing after testing previous solution:

how can trigger transition after period of time?

thank you,

clément

to break solutions 2 major groups, can:

  1. use ruby/rails queueing solution, delayedjob, resque, or sidekiq; or,
  2. use cronjob.

the former tends make sense if you're using 1 of tools or know you're going end using 1 of them. of them require substantial amount of effort going. resque , sidekiq require configuring redis server while delayedjob uses existing database. resque additionally requires plugin schedule jobs, while delayedjob , sidekiq natively support scheduling job. 3 require creating job models , configuring workers run.

the latter's pretty simple assuming have cron access. write script in ruby, , schedule run automatically via cron.

i haven't used state_machine while, should work (if not, gets idea across):

#!/usr/bin/env /path/to/project/bin/rails runner order.where(state: 'confirmed').where("created_at <= #{5.days.ago}").find_each |o|   o.not_received_by_5_days end 

what's going on here? our order object created, enters confirmed state. find orders need little nudge, can run activerecord query find orders in confirmed state 5+ days old. iterate through each record , fire not_received_by_5_days event.

the whole thing managed rails runner, loads rails environment , executes script's code there (just using rails console, without human intervention).

run cron once or twice day (or more if want emails go out more frequently), script find every unattended order that's @ least 5 days old , move through workflow. since code (should) move people new state once not_received_by_5_days event fires, they'll no longer show in subsequent script executions , receive 1 reminder.


Comments

Popular posts from this blog

html5 - What is breaking my page when printing? -

c# - must be a non-abstract type with a public parameterless constructor in redis -

ajax - PHP/JSON Login script (Twitter style) not setting sessions -