如何在块中调用 `super`

How to call `super` in a block

我有一段代码。它是:

class User < ActiveRecord::Base
  def configuration_with_cache
    Rails.cache.fetch("user_#{id}_configuration") do
      configuration_without_cache
    end
  end
  alias_method_chain :configuration, :cache
end

我想去掉臭名昭著的alias_method_chain,所以我决定重构它。这是我的版本:

class User < ActiveRecord::Base
  def configuration
    Rails.cache.fetch("#{id}_agency_configuration") do
      super
    end
  end
end

但是没用。 超级进入了一个新的范围。我怎样才能让它发挥作用? 我得到了 TypeError: can't cast Class,但我误解了它。

您可以在块中使用 Super。

请看这里,有任何问题请告诉我。

直接调用它 'super' 将通过该块。 super(*args, &block)' 也会。

首先,在块中调用 super 会按照您想要的方式运行。一定是你的控制台处于损坏状态(或其他)。

class User
  def professional?
    Rails.cache.fetch("user_professional")  do
      puts 'running super'
      super
    end
  end
end
User.new.professional?
# >> running super
# => false
User.new.professional?
# => false

接下来,这看起来像 Module#prepend was made to help with

module Cacher
  def with_rails_cache(method)
    mod = Module.new do
      define_method method do
        cache_key = "my_cache_for_#{method}"
        Rails.cache.fetch(cache_key) do
          puts "filling the cache"
          super()
        end
      end
    end
    prepend mod
  end
end

class User
  extend Cacher

  with_rails_cache :professional?
end
User.new.professional?
# >> filling the cache
# => false
User.new.professional?
# => false