Sorting a YAML output in an ERB template

In an ERB template used by Puppet, I'm trying to sort a YAML output of a hash to make sure it's always the same output.

Here is what I have so far (in mytest/templates/hash.erb ):

<%=
  class MyHash < Hash
    def to_yaml( opts = {} )
      YAML::quick_emit( self, opts ) do |out|
        out.map( taguri, to_yaml_style ) do |map|
          keys.sort.each do |k|
            v = self[k]
            map.add( k, v )
          end
        end
      end
    end
  end
  myScope = scope.to_hash.reject{|k,v| k.to_s =~ /(uptime|timestamp|free)/}
  MyHash[myScope].to_yaml
-%>

which yields:

$ puppet apply -e 'include mytest' --modulepath .
Failed to parse template mytest/hash.erb:
  Filepath: /usr/lib/ruby/1.8/yaml.rb
  Line: 391
  Detail: wrong argument type String (expected Data)
 at /home/rpinson/bas/puppet/mytest/manifests/init.pp:3 on node foo.example.com

This is the content of mytest/manifests/init.pp :

class mytest {
  notify { 'toto':
    message => template('mytest/hash.erb'),
  }
}

I can't seem to understand where this type Data comes from, and how to cast the parameters properly in order to get this to work…


It turns out, the source of problem is ZAML, YAML replacement which Puppet uses for performance purposes.

It can be proved by testing this erb -template without Puppet .

I'm pretty sure it will work.

I'm investigating to allow to work them together.

UPDATE:

ZAML.dump(MyHash[myScope]) # instead of MyHash[myScope].to_yaml

This may heal problem, at least it does my one that really similar.

链接地址: http://www.djcxy.com/p/61426.html

上一篇: 在ruby模板中按照定义的顺序循环散列

下一篇: 在ERB模板中排序YAML输出