0
votes

I'm building a new XML document using the following code:

doc = Nokogiri::XML::Builder.new(:encoding => 'UTF-8') do
  reginfo {
    client_type_id client_type == :associate ? ASSOCIATE : CLIENT 
    parent_ {
      id_ client_type == :associate ? associate_id : customer_id
      client_type_id client_type == :associate ? ASSOCIATE : CLIENT  
      vsn client_type == :associate ? associate_vsn : customer_vsn
    }
  }
end

The tags above listed as client_type_id show up in the XML file like client_type_id, but that is not the correct XML tag name format. I need them to be client-type-id.

I tried replacing the line with:

:"client-type-id" client_type == :associate ? ASSOCIATE : CLIENT 

but I get:

syntax error, unexpected tIDENTIFIER, expecting '}'
    :"client-type-id" client_type == :associate ? ASSOCIATE : CLIENT 
                                 ^

or:

:"client-type-id" (client_type == :associate ? ASSOCIATE : CLIENT)

but I get:

syntax error, unexpected '(', expecting '}'
        :"client-type-id" (client_type == :associate ? ASSOCIATE : CLIENT)
                           ^

Is there a way to tell Nokogiri::XML::Builder:

  1. on a per-line basis, to use dashes for a tag name and does it have a different syntax?
  2. that for the entire document, during creation or after, to use dashes for all underscores in element names so that it forms correctly formatted XML element names?
1
You can use a string method like .gsub to replace _ with dashes - - Cyzanfar
You are also missing the local variable between the pipes after the do. example: doc = Nokogiri::XML::Builder.new(:encoding => 'UTF-8') do |xml| - Cyzanfar
@Cyzanfar |xml| is not a local variable, it is block variable and since OP did not use it, it might be easily omitted. Block vars are not mandatory. - Aleksei Matiushkin
True, it is a block variable however it is local to the context of the block therefore it is not wrong to call it a local variable - Cyzanfar

1 Answers

1
votes

There is a fancy way of doing this:

Nokogiri::XML::Builder.new(:encoding => 'UTF-8') do |xml|
  ...
  xml.send :"client-type-id", (client_type == :associate ? ASSOCIATE : CLIENT)
  ...
end