首页 > 解决方案 > 调用 `super` 的时机

问题描述

我应该理解这段代码:

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

标签: ruby

解决方案


首先,你需要看到ancestors你的班级会像 [Stealth::MixpanelSessionTracking, Session] 因为你使用prepend.

然后你set首先调用 Stealth::MixpanelSessionTracking 和 Session 类的超级内部set方法,因为祖先链带有前置。


推荐阅读