问题
I am currrently working on a project that has to implement dynamic workflow.
Dynamic: I store workflow's states in database table called wf_steps and the workflow gem has to create
states
for a particular workflow from the database
For that I am trying to use the workflow gem. You can see how it initializes states and corresponding events in the gem's github-page.
My code:
class SpsWorkflow < ActiveRecord::Base
belongs_to :user
has_many :wf_steps
include Workflow
workflow do
# binding.pry
# read wf-states from the database
# for now let event be same for all the states
self.wf_steps.each do |step|
state step.title.to_sym do
event :assign, transitions_to: :assigning
event :hire, transitions_to: :hiring
event :not_hire, transitions_to: :not_hiring
end
end
end
end
Expectation and Problem encountered:
I expected in the code block below the term self.wf_steps
would return my SpsWorkflow
's instance/collection. However the self
keyword returns #<Workflow::Specification:0x000000063e23e8 @meta={}, @states={}>
when I use binding.pry
inside the workflow
method's block ( I commented in the code )
# read wf-states from the database
# for now let event be same for all the states
self.wf_steps.each do |step|
state step.title.to_sym do
Need you help, thanks
EDIT:
I also tried storing the instance in a variable and using the variable inside the block passing to the workflow
method call.
class SpsWorkflow < ActiveRecord::Base
include Workflow
sps_instance = self
But I got the instance of the class SpsWorkflow
like
SpsWorkflow(id: integer, workflow_state: string, assigned_to: integer, title: string, description: string, organization_id: integer, user_id: integer, created_at: datetime, updated_at: datetime)
but I want
#<SpsWorkflow id: 1, workflow_state: "step1", assigned_to: nil, title: "Software Engineer", description: "Hire best engineer", organization_id: nil, user_id: 1, created_at: "2015-08-08 00:58:12", updated_at: "2015-08-08 00:58:12">
回答1:
You have used:
workflow do
self.something
end
self
in the context of this block will refer to the WorkflowSpecification
. If you really want access to the instance of SpsWorkflow
, you may have to pass it into the block or assign it to a different variable and use it there.
回答2:
I finally solved it using a activerecord callback
class SpsWorkflow < ActiveRecord::Base
include Workflow
after_initialize do
sps_instance = self
SpsWorkflow.workflow do
# read wf-states as well as events from the database
sps_instance.wf_steps.each do |step|
state step.title.to_sym do
event :assign, transitions_to: :step2
event :hire, transitions_to: :hire
event :not_hire, transitions_to: :not_hiring
end
end
end
end
belongs_to :user
has_many :wf_steps
end
来源:https://stackoverflow.com/questions/31911077/ror-workflow-gem-i-want-to-implement-dynamic-states-from-database