Search code examples
ruby-on-railsrubyrabl

How to embed CDATA using RABL?


When I try to create a node like:

  node 'test' do
    '<![CDATA[ <HTML></HTML> ]]>'
  end

RABL outputs something like:

<test>&lt;![CDATA[ &lt;HTML&gt;&lt;/HTML&gt; ]]&gt;</test>

I'd like it to output:

<test><![CDATA[ <HTML></HTML> ]]></test>

How to do that?


Solution

  • Rabl's XML renderer uses ActiveSupport's Hash#to_xml internally, so you can use that function's functionality to generate a CDATA block like this:

    node 'test' do
      { '_' => lambda { |x| x[:builder].cdata! '<HTML></HTML>' } }
    end
    

    Note that I've added a "throwaway" key, since to_xml throws the passed key away for a proc. Take a look at the source code in the link above; there might be a better way to handle this.

    Rabl renders the block above for me like:

    <?xml version="1.0" encoding="UTF-8"?>
    <hash>
      <test>
        <![CDATA[<HTML></HTML>]]>
      </test>
    </hash>