eval()中未定义的方法

时间:2016-04-01 05:01:45

标签: ruby-on-rails ruby

Eval()用于评估Rails 4.2模型workflow中的payment_request块。在使用workflow

之前,这是eval
  class PaymentRequest < ActiveRecord::Base
    include Workflow
    def self.load_wf
      workflow do
        state :initial_state do
          event :submit, :transitions_to => :ceo_reviewing
        end
        state :ceo_reviewing do
          event :reject, :transitions_to => :rejected
          event :approve, :transitions_to => :approved
        end
        state :rejected
        state :approved
      end
    end
    ..........
  end

字符串变量spec定义为:

spec = "state :initial_state do
    event :submit, :transitions_to => :ceo_reviewing
  end
  state :ceo_reviewing do
    event :reject, :transitions_to => :rejected
    event :approve, :transitions_to => :approved
  end
  state :rejected
  state :approved"

并重写:

  class PaymentRequest < ActiveRecord::Base
    include Workflow
    def self.load_wf(spec)
      eval("Workflow::ClassMethods.workflow {#{spec}}")    
    end
     ...............
  end

eval生成错误:

undefined method 'workflow' for Workflow::ClassMethods:Module.

workflow是gem中的一个方法:

module Workflow
  module ClassMethods
    attr_reader :workflow_spec
    .....
    def workflow(&specification)
      assign_workflow Specification.new(Hash.new, &specification)
    end
    ......
  end
end

试图在eval中添加绑定并且它不起作用(不确定绑定是否正确使用)。如何eval找到方法workflow&amp;在模型payment_request中执行它?

1 个答案:

答案 0 :(得分:2)

我认为这里的问题是你尝试在方法被正确混合之前调用方法。模块的使用方式是documented on the home page。由于您动态执行此操作,因此您需要尽可能地尝试匹配它。

也就是说,做这样的事情:

class PaymentRequest < ActiveRecord::Base
  include Workflow

  def self.load_wf(spec)
    instance_eval("workflow {#{spec}}")    
  end
end

workflow方法应该在您在此处执行的上下文中定义,即PaymentRequest类,并且使用instance_eval可能会使用正确的绑定进行设置。 eval可能会有用,所以也请尝试。