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
中执行它?
答案 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
可能会有用,所以也请尝试。