我试图在其他方法中使用变量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
我不明白为什么初始化方法最后被触发,我想在aasm do events
的其他方法中也使用变量@t
。我怎么能做到这一点,没有得到@t
是nil
或t method not found
?
aasm
块及其状态定义在类加载时运行。这就是puts "Check Orthography"
运行在puts self.t
之前的原因。
要在实际设置状态时运行代码,可能需要研究回调。我想下面的方法可能对你有用:
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是很常见的。您可能希望遵循此约定,以避免与其他开发人员一起工作时产生混淆。