state-machineaasm

Error when using eval to execute aasm block


We put the whole aasm block in string and eval it in payment_request model. Here is the def:

class PaymentRequest < :ActiveRecord::Base
  include AASM

  def self.load_wf_spec(wf_spec, wf_def_name)
     eval("aasm(:#{wf_def_name})  :column => 'wf_state' {#{wf_spec}}")
  end
end

The error is:

 Failure/Error: eval("aasm(:#{wf_def_name})  :column => 'wf_state' {#{wf_spec}}")

  SyntaxError:
    (eval):1: syntax error, unexpected ':', expecting end-of-input
    aasm(:test)  :column => 'wf_state' {state :...
                  ^
  # ./app/models/payment_requestx/payment_request.rb:11:in `eval'

Here is the value of the variable:

  wf_def_name = 'test'
  wf_spec = "state :initial_state, :initial => true
       state :ceo_reviewing 
       state :approved
       state :stamped
       state :paid
       state :rejected
      event :submit_test do
         transitions :from => :initial_state, :to => :ceo_reviewing
      end
      event :ceo_approve_test do
         transitions :from => :ceo_reviewing, :to => :approved
      end 
      event :ceo_reject_test do
        transitions :from => :ceo_reviewing, :to => :rejected
      end
      event :ceo_rewind_test do
        transitions :from => :ceo_reviewing, :to => :initial_state
      end
      event :stamp_test do
        transitions :from => :approved, :to => :stamped
      end
      event :pay_test do
        transitions :from => :stamped, :to => :paid
      end"

If removing (:test)', then the same error points to next:

Failure/Error: eval("aasm :column => 'wf_state' {#{wf_spec}}")

  SyntaxError:
    (eval):1: syntax error, unexpected '{', expecting end-of-input
    aasm :column => 'wf_state' {state :initial_state, :initial => true
                                ^
  # ./app/models/payment_requestx/payment_request.rb:11:in `eval'

What is missing in the eval?


Solution

  • Here is what it works:

    eval("aasm(:#{wf_def_name}, :column => 'wf_state') {#{def_string}}")