Use YAML with variables

前端 未结 5 1013
你的背包
你的背包 2020-11-28 22:47

Are variables within YAML files possible? For example:

theme:
  name: default
  css_path: compiled/themes/$theme.name
  layout_path: themes/$theme.name
         


        
5条回答
  •  温柔的废话
    2020-11-28 23:29

    This is an old post, but I had a similar need and this is the solution I came up with. It is a bit of a hack, but it works and could be refined.

    require 'erb'
    require 'yaml'
    
    doc = <<-EOF
      theme:
      name: default
      css_path: compiled/themes/<%= data['theme']['name'] %>
      layout_path: themes/<%= data['theme']['name'] %>
      image_path: <%= data['theme']['css_path'] %>/images
      recursive_path: <%= data['theme']['image_path'] %>/plus/one/more
    EOF
    
    data = YAML::load("---" + doc)
    
    template = ERB.new(data.to_yaml);
    str = template.result(binding)
    while /<%=.*%>/.match(str) != nil
      str = ERB.new(str).result(binding)
    end
    
    puts str
    

    A big downside is that it builds into the yaml document a variable name (in this case, "data") that may or may not exist. Perhaps a better solution would be to use $ and then substitute it with the variable name in Ruby prior to ERB. Also, just tested using hashes2ostruct which allows data.theme.name type notation which is much easier on the eyes. All that is required is to wrap the YAML::load with this

    data = hashes2ostruct(YAML::load("---" + doc))
    

    Then your YAML document can look like this

    doc = <<-EOF
      theme:
      name: default
      css_path: compiled/themes/<%= data.theme.name %>
      layout_path: themes/<%= data.theme.name %>
      image_path: <%= data.theme.css_path %>/images
      recursive_path: <%= data.theme.image_path %>/plus/one/more
    EOF
    

提交回复
热议问题