【问题标题】:How to write a file that is both valid ruby syntax and valid YAML syntax如何编写既是有效的 ruby​​ 语法又是有效的 YAML 语法的文件
【发布时间】:2014-04-10 08:33:22
【问题描述】:

为了让我的应用程序只有一个配置点,我需要创建一个 YAML 配置文件,该文件也是有效的 ruby​​ 代码。 IE。一个混合语法文件,可以解析为 YAML,也可以解析为 ruby​​。

我的应用程序是一套由god gem 管理的进程。我想为每个新的配置文件加载一组新的维护进程(监视)。

God 允许加载定义了新手表的新 app.god (ruby) 文件,但我不想要 app.god 和 app.yml,只有一个文件。最简单的可能是只拥有 app.god 文件并在其中包含配置,但我更喜欢 yml 文件的想法,它也是有效的 ruby​​ 代码。

【问题讨论】:

    标签: ruby yaml god polyglot


    【解决方案1】:
    #I found this that might be helpful:
    #This is a valid ruby and a valid YAML file
    #Comments are the same in YAML and ruby
    
    true ?true: 
    - <<YAML.to_i
    # At this point in ruby it is the contents of a here doc (that will be 
    # converted to an integer and negated if true happens not to be true)
    # In YAML it is a hash with the first entry having key "true ?true"
    # representing a list containing the string "- <<YAML.to_i"
    # If your YAML object should be a list not a hash you could remove the first line
    
    any_valid_yaml:  from here
    a_list:
    - or
    - anything
    - really
    #Then mark the end of the YAML document with 
    ---
    #And YAML is done and ignores anything from here on
    #Next terminate the ruby here document
    YAML
    
    #Now we're in ruby world
    
    @this = "pure ruby"
    
    def anything(ruby)
       "here"
    end
    

    【讨论】:

      猜你喜欢
      • 2022-12-22
      • 1970-01-01
      • 1970-01-01
      • 2017-07-21
      • 1970-01-01
      • 2019-10-09
      • 1970-01-01
      • 1970-01-01
      • 2015-10-07
      相关资源
      最近更新 更多