Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How call custom class method, when Spree order finalize! method executed

I am developing spree extension. What I want to do, is to create new database record when order finalized. I need some suggestion how to do it. How I understand one way is to create custom method in order class, and register new hook (where I should register new hook? in initializer?). Other way is to use Activators, but I don't have any idea how to subscribe events. And where I should put code which subscribe order events.

module Spree
  class Credit < ActiveRecord::Base
     def create_new_line(order) 
        #I need call this method when order finalized    
     end  
  end
end 

I found solution. My order decorator looks like this.

Spree::Order.class_eval do
  register_update_hook :add_user_credits
  def add_user_credits
    if (!self.user.nil? and !self.completed_at.nil?)
      # do some stuff, only for registered users and when order complete
    end
  end
end
like image 776
dpa Avatar asked Dec 25 '22 13:12

dpa


1 Answers

In your solution I think that the hook will be called every time you update the oder. So if you change something after the order is completed that method will be called again. If it's like this by design that could be the right solution anyway Spree suggests to directly use state machine callback to do stuff like this. For example:

Spree::Order.class_eval do
  state_machine do
    after_transition :to => :complete, :do => :add_user_credits
  end

  def add_user_credits        
    # do some stuff
  end
end

This way the code will be executed immediately after the order goes into the complete state.

like image 134
kennyadsl Avatar answered Apr 09 '23 05:04

kennyadsl