【问题标题】:How to keep strings in yaml from getting converted to times如何防止 yaml 中的字符串转换为时间
【发布时间】:2010-02-18 05:49:20
【问题描述】:

我有一个包含一些时间的 yaml 文件:

  hours:
    - 00:00:00
    - 00:30:00
    - 01:00:00

但是,一旦我阅读它们,它们就会被转换为时间(以秒为单位),但我希望它们暂时保留为字符串,以便我可以进行转换。以下是我的阅读方式:

  def daily_hours
    DefaultsConfig.hours.collect {|hour|
      logger.info { hour.to_s }
    }
  end

它正在输出:

0 1800 3600

但我希望字符串保持不变,我可以将它们转换为时间,例如:

12:00am 12:30am 1:00am

为什么它们会自动转换,我该如何阻止它?

这是 DefaultConfig 类:

class DefaultsConfig  
  def self.load
    config_file = File.join(Rails.root, "config", "defaults.yml")

    if File.exists?(config_file)
      config = ERB.new(File.read(config_file)).result
      config = YAML.load(config)[Rails.env.to_sym]
      config.keys.each do |key|
        cattr_accessor key
        send("#{key}=", config[key])
      end
    end
  end
end
DefaultsConfig.load

【问题讨论】:

  • DefaultConfigs如何设置?
  • 那只是在yaml文件中读取的类。它使我可以访问“小时”,这是您在帖子的第一个灰色框中看到的。我将代码添加到帖子中。

标签: ruby-on-rails ruby yaml


【解决方案1】:

如果将值括在单引号内,YAML 解析器会将值视为字符串。

hours:
    - '00:00:00'
    - '00:30:00'
    - '01:00:00'

现在,当您访问该值时,您将得到一个字符串而不是时间

DefaultsConfig.hours[0] # returns "00:00:00"

【讨论】:

  • 谢谢,这行得通!奇怪的是它在没有单引号的情况下转换它!
  • 本质上,您通过将值括在引号中将其转换为字符串。更多详情请参考本文eng.genius.com/blog/2009/04/15/yaml-gotchas
【解决方案2】:

不带引号或标记的标量是implicit type 的主题。您可以使用引号或显式标记:

hours:
       - '00:00:01'
       - "00:00:02"
       - !!str "00:00:03"

【讨论】:

    猜你喜欢
    • 2020-02-20
    • 2021-11-21
    • 2018-04-12
    • 1970-01-01
    • 1970-01-01
    • 2023-02-09
    • 1970-01-01
    • 2011-06-18
    • 1970-01-01
    相关资源
    最近更新 更多