调用`super`的时间

时间:2018-10-18 13:13:25

标签: ruby

我应该理解这段代码:

module Stealth
  module MixpanelSessionTracking
    def set(flow:, state:)
      retval = super

      if ENV['MIXPANEL_PROJECT_TOKEN'].present?
        mixpanel = Stealth::Mixpanel.new
        mixpanel.tracker.track(user_id, 'State Change', {
          'flow' => flow,
          'state' => state
        })
      end

      retval
    end
  end

  class Session
    prepend Stealth::MixpanelSessionTracking
  end

end

为什么要在方法定义的末尾调用super变量之前将setval设置为retval变量?

我可以在方法定义的末尾使用super吗?

编辑:

祖先类方法:

module Stealth
  class Session
    (...)
    def set(flow:, state:)
      store_current_to_previous(flow: flow, state: state)

      @flow = nil
      @session = canonical_session_slug(flow: flow, state: state)

      Stealth::Logger.l(topic: "session", message: "User #{user_id}: setting session to #{flow}->#{state}")
      $redis.set(user_id, session)
    end
    (...)
  end
end

2 个答案:

答案 0 :(得分:0)

首先,您需要在课程中看到ancestors,就像[Stealth :: MixpanelSessionTracking,Session]导致您使用prepend一样。

然后您调用set,因为祖先链在前面,所以您首先调用Stealth :: MixpanelSessionTracking和Session类的set中的super内部方法。

答案 1 :(得分:0)

在Ruby文档thereanswer on stackoverflowsuper可以很好地修饰:

  

super的行为类似于方法调用,该方法调用超类的方法实现。在您的示例中,return关键字从Parent :: test返回并继续执行Child :: test,就像其他方法调用一样。

在您的情况下,有人将retval定义为super,然后在代码中使用retval而不是super。