سؤال

I was reading through Dalli's source code and I found this...

module ActionDispatch
  module Session
    class DalliStore < AbstractStore
      def initialize(app, options = {})
        # Support old :expires option
        options[:expire_after] ||= options[:expires]

        super

        @default_options = { :namespace => 'rack:session' }.merge(@default_options)

        @pool = options[:cache] || begin
          Dalli::Client.new(
              @default_options[:memcache_server], @default_options)
        end
        @namespace = @default_options[:namespace]

        @raise_errors = !!@default_options[:raise_errors]

        super
      end

      .... rest of class definition

What stood out to me is that super was called twice during initialize. I've never saw this sort of ruby idiom before. Why would you ever want to do this?

هل كانت مفيدة؟

المحلول

So I went to the repo to hunt down AbstractStore which is part of rails' actionpack. No initialize there so no behaviour that would warrant such a use. AbstractStore though also inherits from Rack::Session::Abstract::ID. Sure enough now we have the meat of it:

def initialize(app, options={})
  @app = app
  @default_options = self.class::DEFAULT_OPTIONS.merge(options)
  @key = @default_options.delete(:key)
  @cookie_only = @default_options.delete(:cookie_only)
  initialize_sid
end

Looks like the first init is to get those instance variables set up. Then use and add to them which is unsurprising: the last super though... I'm gonna take a wild guess and say that it won't do anything useful and is superfluous. I looked at core classes that inherit from AbstractStore and none of them uses multiple calls to super. Maybe a bug[1]. Open an issue on github and see where it leads.

[1] This seems somewhat related

EDIT: I have overlooked another thing though, super is on the last line and thus is the return value. This might actually be a better explanation.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top