首页 > 解决方案 > 数组作为 Rails.cache.fetch 方法中的第一个参数

问题描述

我正在阅读有关 Rails 缓存获取方法的信息。我阅读的所有示例都将字符串作为方法中的第一个参数传递。但是,当我阅读 Rails 项目的代码时,我看到了一个array passed as the first argument in cache fetch method.

  def self.get_new_sitemap(https_version = false)
    Rails.cache.fetch(['sitemap_city_block', https_version], expires_in: 5.days) do
      modified_key = 'key1'
      LocalCache.set(modified_key, Date.today)

      protocol = (https_version ? 'https' : 'http')
      url_list = get_sitemap_urls(https_version)
      content = Nokogiri::XML::Builder.new do |xml|
        xml.urlset('xmlns' => "http://www.sitemaps.org/schemas/sitemap/0.9",
          'xmlns:xsi' => "http://www.w3.org/2001/XMLSchema-instance",
          'xsi:schemaLocation' => "http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd") {
          url_list.each { |url|
            xml.url {
              xml.loc url[:loc]
              xml.lastmod url[:lastmod] if url[:lastmod].present?
            }
          }
        }
      end.to_xml
    end
  end

我无法理解传递数组背后的逻辑。在某些情况下,会传递大小为 3 的数组。
任何帮助将不胜感激。

标签: ruby-on-railsruby

解决方案


查看 rails 源代码揭示了(私有)方法Rails.cache.expanded_key

这个方法做了一些事情。特别是,它调用:key.to_param. 这会将数组转换为字符串

因此,换句话说,您可以使用Rails.cache.fetch数组(或哈希!)进行调用,但在后台缓存键仍将是一个字符串。


推荐阅读