我正在尝试在t
传递的其他方法中使用变量initialize
。
这是我的术语:
class Term
include AASM
attr_accessor :t
def initialize(term)
@t = term
puts self.t
end
aasm do
state :Initialized, :initial => true
state :OrthographyChecked
event :Orthography do
puts "Check Orthography"
# use @t variable here
transitions :from => :Initialized, :to => :UniquenessChecked
end
# .. more events
end
end
term = Term.new("textstring")
我创建了一个新实例,但是打印文本的顺序并不是我所期望的。我明白了:
Check Orthography #from Orthography event
textstring #from initialize method
我不明白为什么lastize方法最后被触发,我想在@t
的其他方法中也使用变量aasm do events
。如果不@t
nil
或t method not found
,我怎么能这样做?
答案 0 :(得分:2)
aasm
块及其状态定义。这就是puts "Check Orthography"
在puts self.t
之前运行的原因。
要在实际设置状态时运行代码,您可能需要调查callbacks。我猜以下内容可能适合您:
class Term
include AASM
attr_accessor :t
def initialize(term)
@t = term
puts "t in initialize: #{t}"
end
aasm do
state :Initialized, :initial => true
state :OrthographyChecked
event :Orthography do
before do
puts "Check Orthography"
puts "t in Orthography: #{t}"
end
transitions :from => :Initialized, :to => :UniquenessChecked
end
# .. more events
end
end
term = Term.new("textstring")
term.Orthography
顺便说一下,在Ruby中使用下划线的method_names和state_names而不是CamelCase是很常见的。您可能希望遵循此约定以避免与其他开发人员一起工作时出现混淆。