开发者

How to keep strings in yaml from getting converted to times

开发者 https://www.devze.com 2022-12-20 23:54 出处:网络
I have a yaml file which contains some times: hours: - 00:00:00 - 00:30:00 - 01:00:00 But as soon as I read them they get converted to time (in seconds), but I want them to remain as strings for a

I have a yaml file which contains some times:

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

But as soon as I read them they get converted to time (in seconds), but I want them to remain as strings for a moment so i can do the conversion. Here's how I'm reading them:

  def daily_hours
   开发者_运维问答 DefaultsConfig.hours.collect {|hour|
      logger.info { hour.to_s }
    }
  end

And it's outputting:

0 1800 3600

But I want the strings to remain unchanged to I can convert them to times such as:

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

Why are they getting converted automatically, and how can I stop it?

Here's the DefaultConfig class:

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


If you enclose the value within single quotes, the YAML parser will treat the value as a string.

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

Now when you access the value you will get a string instead of time

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


Scalar without quotes or tag is a subject of implicit type. You can use quotes or explicit tag:

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号