0

我正在尝试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

我不明白为什么最后会触发初始化方法,我@t也想在aasm do events. 我怎么能做到这一点,没有@t得到nilor t method not found

4

1 回答 1

2

aasm加载类时运行块及其状态定义。这就是为什么要puts "Check Orthography"运行 before的原因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 是很常见的。在与其他开发人员一起工作时,您可能希望遵循此约定以避免混淆。

于 2016-10-30T14:55:09.077 回答