【问题标题】:Array as first argument in Rails.cache.fetch method数组作为 Rails.cache.fetch 方法中的第一个参数
【发布时间】:2020-10-19 17:54:49
【问题描述】:

我正在阅读有关 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-rails ruby


    【解决方案1】:

    查看 rails 源代码会发现(私有)方法Rails.cache.expanded_key

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

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

    【讨论】:

      猜你喜欢
      • 2018-03-09
      • 1970-01-01
      • 2021-01-09
      • 1970-01-01
      • 2019-06-27
      • 1970-01-01
      • 2014-04-15
      • 1970-01-01
      • 2016-08-19
      相关资源
      最近更新 更多