### Install Builder Gem Source: https://github.com/jimweirich/builder/blob/master/doc/releases/builder-2.1.1.rdoc Provides the command to install the Builder gem using RubyGems. This is the recommended method for obtaining and installing the library. Administrator privileges may be required. ```Shell gem install builder ``` -------------------------------- ### Generating XML with Namespaces and Attributes using Builder Source: https://context7.com/jimweirich/builder/llms.txt Demonstrates how to create XML documents with namespaces, attributes, and nested elements using the Builder::XmlMarkup class. It shows examples for simple namespaces, namespaces with attributes, and complex structures like OWL/RDF. ```ruby require 'builder' # Simple namespace xml = Builder::XmlMarkup.new xml.rdf :RDF xml.target! #=> "" # Namespace with attributes and nested content xml = Builder::XmlMarkup.new(:indent => 2) xml.instruct! xml.soap :Envelope, "xmlns:soap" => "http://schemas.xmlsoap.org/soap/envelope/", "xmlns:xsi" => "http://www.w3.org/2001/XMLSchema-instance" do |x| x.soap :Header do x.auth :Token, "abc123", "xmlns:auth" => "http://example.com/auth" end x.soap :Body do x.m :GetUser, "xmlns:m" => "http://example.com/api" do x.m :UserId, 42 end end end puts xml.target! # Output: # # # # abc123 # # # # 42 # # # # OWL/RDF example with multiple namespaces xml = Builder::XmlMarkup.new(:indent => 2) xml.instruct! xml.rdf :RDF, "xmlns:rdf" => :"&rdf;", "xmlns:rdfs" => :"&rdfs;", "xmlns:owl" => :"&owl;" do |x| x.owl :Class, "rdf:ID" => "Person" do x.rdfs :label, "Person" x.rdfs :subClassOf, "rdf:resource" => "#Agent" end end puts xml.target! ``` -------------------------------- ### Generate basic XML markup with Builder Source: https://github.com/jimweirich/builder/blob/master/README.md Demonstrates how to initialize an XmlMarkup builder and generate a simple XML string using block syntax. ```ruby require 'rubygems' require_gem 'builder', '~> 2.0' builder = Builder::XmlMarkup.new xml = builder.person { |b| b.name("Jim"); b.phone("555-1234") } # xml => Jim555-1234 ``` -------------------------------- ### Builder::XmlMarkup Initialization and Usage Source: https://github.com/jimweirich/builder/blob/master/README.md Explains how to initialize the XmlMarkup class and generate XML structure with optional indentation and target output. ```APIDOC ## POST /Builder::XmlMarkup ### Description Initializes a new XML builder instance. This allows for the generation of XML markup through method chaining or block-based nesting. ### Method POST (Constructor) ### Parameters #### Request Body - **target** (Object) - Optional - The output stream (e.g., STDOUT or a File object). Defaults to a string buffer. - **indent** (Integer) - Optional - Number of spaces for indentation. If provided, the output will be pretty-printed. ### Request Example ```ruby builder = Builder::XmlMarkup.new(:target => STDOUT, :indent => 2) ``` ### Response #### Success Response (200) - **xml_output** (String/Stream) - The generated XML content. #### Response Example ```xml Jim 555-1234 ``` ``` -------------------------------- ### Building a Complete XML Document Source: https://context7.com/jimweirich/builder/llms.txt Shows how to construct a well-formed XML document including the XML declaration, namespaces, and nested structured content like an RSS feed. ```ruby require 'builder' xml = Builder::XmlMarkup.new(:indent => 2) xml.instruct! :xml, :version => "1.0", :encoding => "UTF-8" xml.rss(:version => "2.0", "xmlns:atom" => "http://www.w3.org/2005/Atom") do |rss| rss.channel do |channel| channel.title("My Blog") channel.atom :link, :href => "http://example.com/feed.xml", :rel => "self", :type => "application/rss+xml" channel.item do |item| item.title("First Post") item.pubDate(Time.now.strftime("%a, %d %b %Y %H:%M:%S %z")) end end end puts xml.target! ``` -------------------------------- ### Generate XML Markup with Builder::XmlMarkup Source: https://github.com/jimweirich/builder/blob/master/doc/releases/builder-2.1.1.rdoc Demonstrates how to use the Builder::XmlMarkup library to programmatically create XML. It shows initialization with target and indentation options, and a nested structure for creating elements and text content. Note the change in attribute escaping behavior from version 1.x to 2.x. ```Ruby builder = Builder::XmlMarkup.new(:target=>STDOUT, :indent=>2) builder.person { |b| b.name("Jim"); b.phone("555-1234") } ``` -------------------------------- ### Generate XML Markup with Builder Source: https://github.com/jimweirich/builder/blob/master/doc/releases/builder-1.2.4.rdoc Demonstrates how to initialize an XmlMarkup object and use a block-based syntax to generate nested XML elements. The output is directed to STDOUT with specified indentation. ```ruby builder = Builder::XmlMarkup.new(:target=>STDOUT, :indent=>2) builder.person { |b| b.name("Jim"); b.phone("555-1234") } puts builder.target! ``` -------------------------------- ### Configure XML output with indentation and target Source: https://github.com/jimweirich/builder/blob/master/README.md Shows how to configure the builder to output to a specific target (like STDOUT) with custom indentation settings. ```ruby require 'rubygems' require_gem 'builder' builder = Builder::XmlMarkup.new(:target=>STDOUT, :indent=>2) builder.person { |b| b.name("Jim"); b.phone("555-1234") } ``` -------------------------------- ### Builder::XmlMarkup.new - Create XML Markup Builder Source: https://context7.com/jimweirich/builder/llms.txt Demonstrates how to instantiate and use Builder::XmlMarkup with various configuration options for output, indentation, quoting, and nil handling. ```APIDOC ## Builder::XmlMarkup.new - Create XML Markup Builder ### Description Creates a new XML markup builder instance with configurable options for output target, indentation, quote style, and nil handling. The builder accepts any object responding to `<<` as a target and returns generated XML as a string by default. ### Method `Builder::XmlMarkup.new(options = {})` ### Parameters #### Options - **:target** (IO object or String) - The output stream or string to write XML to. Defaults to an internal string buffer. - **:indent** (Integer) - The number of spaces for each indentation level. Enables pretty-printing. - **:quote** (:single or :double) - The type of quotes to use for attribute values. Defaults to :double. - **:explicit_nil_handling** (Boolean) - If true, `nil` values are rendered as `nil="true"`. Defaults to false. - **:margin** (Integer) - The initial indentation level. ### Request Example ```ruby require 'builder' # Basic builder with default settings (returns string) xml = Builder::XmlMarkup.new xml.person { |x| x.name("Alice"); x.email("alice@example.com") } puts xml.target! #=> "Alicealice@example.com" # Builder with pretty-printing (2-space indentation) xml = Builder::XmlMarkup.new(:indent => 2) xml.users do |x| x.user(:id => 1) do x.name("Bob") x.role("admin") end end puts xml.target! #=> "\n \n Bob\n admin\n \n\n" # Builder writing directly to STDOUT xml = Builder::XmlMarkup.new(:target => STDOUT, :indent => 2) xml.message { |x| x.text("Hello World") } # Builder with single quotes for attributes xml = Builder::XmlMarkup.new(:quote => :single) xml.link(:href => "http://example.com") puts xml.target! #=> "" # Builder with initial margin (indentation level) xml = Builder::XmlMarkup.new(:indent => 2, :margin => 2) xml.nested { |x| x.content("indented") } puts xml.target! #=> " \n indented\n \n" # Builder with explicit nil handling xml = Builder::XmlMarkup.new(:explicit_nil_handling => true) xml.tag!("value", nil) puts xml.target! #=> "" ``` ### Response #### Success Response (200) - **String**: The generated XML markup. #### Response Example ```json { "example": "Alicealice@example.com" } ``` ``` -------------------------------- ### Create XML Markup Builder with Builder::XmlMarkup.new Source: https://context7.com/jimweirich/builder/llms.txt Instantiates a Builder::XmlMarkup object to generate XML. Supports configurations for output target, indentation, quote style, and nil handling. By default, it returns the generated XML as a string. ```ruby require 'builder' # Basic builder with default settings (returns string) xml = Builder::XmlMarkup.new xml.person { |x| x.name("Alice"); x.email("alice@example.com") } xml.target! #=> "Alicealice@example.com" # Builder with pretty-printing (2-space indentation) xml = Builder::XmlMarkup.new(:indent => 2) xml.users do |x| x.user(:id => 1) do x.name("Bob") x.role("admin") end end xml.target! #=> "\n \n Bob\n admin\n \n\n" # Builder writing directly to STDOUT xml = Builder::XmlMarkup.new(:target => STDOUT, :indent => 2) xml.message { |x| x.text("Hello World") } # Builder with single quotes for attributes xml = Builder::XmlMarkup.new(:quote => :single) xml.link(:href => "http://example.com") xml.target! #=> "" # Builder with initial margin (indentation level) xml = Builder::XmlMarkup.new(:indent => 2, :margin => 2) xml.nested { |x| x.content("indented") } xml.target! #=> " \n indented\n \n" # Builder with explicit nil handling xml = Builder::XmlMarkup.new(:explicit_nil_handling => true) xml.tag!("value", nil) xml.target! #=> "" ``` -------------------------------- ### Ruby: Generate XML Declaration with Builder Source: https://context7.com/jimweirich/builder/llms.txt Demonstrates how to insert XML processing instructions, including the standard XML declaration and custom ones. It shows how to specify version, encoding, and standalone attributes. ```ruby require 'builder' # Default XML declaration xml = Builder::XmlMarkup.new xml.instruct! xml.target! #=> "" # XML declaration with custom encoding xml = Builder::XmlMarkup.new xml.instruct!(:xml, :encoding => "ISO-8859-1") xml.target! #=> "" # XML declaration with standalone attribute xml = Builder::XmlMarkup.new xml.instruct!(:xml, :version => "1.1", :encoding => "UTF-8", :standalone => "yes") xml.target! #=> "" # Custom processing instruction (e.g., for stylesheets) xml = Builder::XmlMarkup.new(:indent => 2) xml.instruct! xml.instruct!("xml-stylesheet", :type => "text/xsl", :href => "transform.xsl") xml.root do |x| x.data("content") end xml.target! #=> "\n\n\n content\n\n" ``` -------------------------------- ### Generate XML Processing Instructions in Ruby Source: https://github.com/jimweirich/builder/blob/master/README.md Shows how to create XML processing instructions, such as the XML declaration. It supports custom instructions and defaults to 'xml' with version 1.0 and UTF-8 encoding if not specified. ```ruby xml_markup.instruct! :xml, :version=>"1.0", :encoding=>"UTF-8" #=> ``` -------------------------------- ### Complete XML Document Construction Source: https://context7.com/jimweirich/builder/llms.txt Shows how to build a full, well-formed XML document including declarations, namespaces, and nested structures. ```APIDOC ## Complete XML Document Construction ### Description Demonstrates building a complex XML document such as an RSS feed, including XML instructions and namespace declarations. ### Method N/A (Library Method) ### Request Example ```ruby xml = Builder::XmlMarkup.new(:indent => 2) xml.instruct! :xml, :version => "1.0", :encoding => "UTF-8" xml.rss(:version => "2.0") { |rss| ... } ``` ### Response - **output** (String) - A fully formatted, valid XML document. ``` -------------------------------- ### Retrieving Generated XML with Builder's target! Method Source: https://context7.com/jimweirich/builder/llms.txt Explains how to use the `target!` method to retrieve the final generated XML markup from a Builder object. It covers obtaining the XML string, understanding the return value of tag methods, and using custom target objects for collecting XML parts. ```ruby require 'builder' # Get XML string from builder xml = Builder::XmlMarkup.new(:indent => 2) xml.instruct! xml.root do |x| x.item("one") x.item("two") end result = xml.target! puts result # Output: # # # one # two # # Return value from tag methods is the target xml = Builder::XmlMarkup.new output = xml.greeting("Hello World") puts output == xml.target! #=> true # Using custom target object class XmlCollector attr_reader :parts def initialize @parts = [] end def <<(str) @parts << str self end end collector = XmlCollector.new xml = Builder::XmlMarkup.new(:target => collector) xml.root { |x| x.child("content") } puts collector.parts.inspect #=> ["", "", "content", "", ""] ``` -------------------------------- ### Ruby: Use XML Namespaces with Builder Source: https://context7.com/jimweirich/builder/llms.txt Demonstrates how to handle XML namespaces in Builder by passing a symbol as the first argument to a tag method. The symbol acts as the namespace prefix. ```ruby require 'builder' # Example usage of XML namespaces (code not provided in original text, conceptual example) xml = Builder::XmlMarkup.new xml.instruct! xml.ns(:xhtml, "http://www.w3.org/1999/xhtml") do |x| x.xhtml!(:body) do |b| b.p("Hello, world!") end end puts xml.target! # Expected Output (conceptual): # # # Hello, world! # ``` -------------------------------- ### Builder::XmlMarkup Generation Source: https://context7.com/jimweirich/builder/llms.txt Demonstrates how to generate XML strings using XmlMarkup, including handling attribute escaping and special characters. ```APIDOC ## Builder::XmlMarkup Generation ### Description Generates XML markup strings. String attributes are automatically escaped, while symbol attributes are treated as raw text (useful for entity references). ### Method N/A (Library Method) ### Parameters - **attributes** (Hash) - Key-value pairs representing XML attributes. ### Request Example ```ruby xml = Builder::XmlMarkup.new xml.company(:name => "Smith & Sons", :slogan => "Quality \"Guaranteed\"") xml.target! ``` ### Response - **output** (String) - The generated XML string with escaped characters. ``` -------------------------------- ### Ruby: Insert XML Comments with Builder Source: https://context7.com/jimweirich/builder/llms.txt Shows how to insert XML comments into the generated markup using the `comment!` method. Comments are automatically formatted with indentation when enabled. ```ruby require 'builder' # Simple comment xml = Builder::XmlMarkup.new xml.comment!("This is a comment") xml.target! #=> "" # Comment within nested structure xml = Builder::XmlMarkup.new(:indent => 2) xml.config do |x| x.comment!("Database configuration") x.database do x.host("localhost") x.port(5432) end x.comment!("Cache settings") x.cache do x.enabled(true) x.ttl(3600) end end puts xml.target! # Output: # # # # localhost # 5432 # # # # true # 3600 # # ``` -------------------------------- ### tag! - Create XML Elements with Dynamic Names Source: https://context7.com/jimweirich/builder/llms.txt Explains how to use the `tag!` method for creating XML elements when tag names are dynamic, contain special characters, or conflict with Ruby reserved words. ```APIDOC ## tag! - Create XML Elements with Dynamic Names ### Description Creates an XML tag with a specified name, useful when tag names contain characters not allowed in Ruby identifiers or when the tag name is determined at runtime. Accepts text content, attributes hash, and optional block for nested content. ### Method `tag!(name, content = nil, attributes = {}, &block)` ### Parameters - **name** (String) - The name of the XML tag. Can include special characters. - **content** (String, optional) - The text content of the tag. - **attributes** (Hash, optional) - A hash of attributes for the tag. - **block** (Proc, optional) - A block to define nested elements. ### Request Example ```ruby require 'builder' xml = Builder::XmlMarkup.new # Tag with special characters in name xml.tag!("SOAP:Envelope") { |x| x.tag!("SOAP:Body", "content") } puts xml.target! #=> "content" # Tag with attributes and text xml = Builder::XmlMarkup.new xml.tag!("custom-element", "Hello", :id => 123, :class => "highlight") puts xml.target! #=> "Hello" # Dynamic tag names from variables xml = Builder::XmlMarkup.new(:indent => 2) tag_name = "dynamic-tag" attributes = { :version => "1.0", :type => "custom" } xml.tag!(tag_name, attributes) do |x| x.tag!("sub-item", "Value 1") x.tag!("sub-item", "Value 2") end puts xml.target! #=> "\n Value 1\n Value 2\n\n" # Tag with Ruby reserved words xml = Builder::XmlMarkup.new xml.tag!("class", :id => 1) { |x| x.tag!("loop", "content") } puts xml.target! #=> "content" ``` ### Response #### Success Response (200) - **String**: The generated XML markup. #### Response Example ```json { "example": "content" } ``` ``` -------------------------------- ### Handle XML Namespaces in Ruby Source: https://github.com/jimweirich/builder/blob/master/README.md Explains how to incorporate XML namespaces into tags by prefixing the tag name with a namespace symbol. This allows for structured XML with namespace qualifications. ```ruby xml.SOAP :Envelope do ... end ``` -------------------------------- ### Enable UTF-8 Support in Ruby Builder Source: https://github.com/jimweirich/builder/blob/master/README.md Demonstrates how to configure Builder for UTF-8 output by setting the XML encoding and the $KCODE variable. This ensures correct handling of international characters. ```ruby $KCODE = 'UTF8' xml = Builder::Markup.new xml.instruct!(:xml, :encoding => "UTF-8") xml.sample("Iñtërnâtiônàl") xml.target! => "Iñtërnâtiônàl" ``` -------------------------------- ### instruct! - XML Declaration Source: https://context7.com/jimweirich/builder/llms.txt Inserts XML processing instructions into the markup. Used primarily for the XML declaration header. ```APIDOC ## instruct! (XML Declaration) ### Description Inserts XML processing instructions. When called without arguments, it generates a standard XML declaration (version 1.0, UTF-8). ### Method N/A (Method call on Builder::XmlMarkup object) ### Parameters - **target** (Symbol) - Optional - The processing instruction target (e.g., :xml). - **attributes** (Hash) - Optional - Attributes for the instruction (e.g., :version, :encoding, :standalone). ### Request Example xml.instruct!(:xml, :version => "1.1", :encoding => "UTF-8") ### Response - **Output** (String) - "" ``` -------------------------------- ### Nested markup block usage Source: https://github.com/jimweirich/builder/blob/master/README.md Demonstrates the standard practice of passing the builder object into nested blocks to ensure correct tag generation. ```ruby xml_markup = Builder::XmlMarkup.new xml_markup.div { |xml| xml.strong("text") } ``` -------------------------------- ### Generate XML Entity Declarations in Ruby Source: https://github.com/jimweirich/builder/blob/master/README.md Illustrates how to declare XML entities, including DOCTYPE declarations and element definitions. It supports symbols and strings as parameters, with strings being enclosed in double quotes. ```ruby xml_markup.declare! :DOCTYPE, :chapter, :SYSTEM, "../dtds/chapter.dtd" #=> ``` ```ruby xml_markup.declare! :ELEMENT, :chapter, :"(title,para+)" #=> ``` ```ruby @xml_markup.declare! :DOCTYPE, :chapter do |x| x.declare! :ELEMENT, :chapter, :"(title,para+)" x.declare! :ELEMENT, :title, :"(#PCDATA)" x.declare! :ELEMENT, :para, :"(#PCDATA)" end #=> ]> ``` -------------------------------- ### Ruby: Declare DTDs and Entities with Builder Source: https://context7.com/jimweirich/builder/llms.txt Explains how to use the `declare!` method to insert XML declarations for DTDs, elements, entities, and other document type definitions. It supports various declaration types and nesting. ```ruby require 'builder' # Simple DOCTYPE declaration xml = Builder::XmlMarkup.new xml.declare!(:DOCTYPE, :html) xml.target! #=> "" # DOCTYPE with system identifier xml = Builder::XmlMarkup.new xml.declare!(:DOCTYPE, :chapter, :SYSTEM, "../dtds/chapter.dtd") xml.target! #=> " # DOCTYPE with public identifier xml = Builder::XmlMarkup.new xml.declare!(:DOCTYPE, :html, :PUBLIC, "-//W3C//DTD XHTML 1.0 Strict//EN", "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd") xml.target! #=> " # Nested declarations (internal DTD subset) xml = Builder::XmlMarkup.new(:indent => 2) xml.declare!(:DOCTYPE, :chapter) do |x| x.declare!(:ELEMENT, :chapter, :"(title,para+)") x.declare!(:ELEMENT, :title, :"(#PCDATA)") x.declare!(:ELEMENT, :para, :"(#PCDATA)") x.declare!(:ATTLIST, :chapter, :id, :ID, :"#REQUIRED") end puts xml.target! # Output: # # # # # ]> ``` -------------------------------- ### Ruby: Insert CDATA Sections with Builder Source: https://context7.com/jimweirich/builder/llms.txt Illustrates how to create CDATA sections for including unparsed character data. The `cdata!` method automatically handles escaping of the `]]>` sequence. ```ruby require 'builder' # Basic CDATA section xml = Builder::XmlMarkup.new xml.cdata!("This is unparsed data & special symbols") xml.target! #=> " data & special symbols]]>" # CDATA with script content xml = Builder::XmlMarkup.new(:indent => 2) xml.html do |x| x.head do x.script(:type => "text/javascript") do x.cdata!("function test() { if (a < b && c > d) { return true; } }") end end end puts xml.target! # Output: # # # # # # CDATA with embedded close sequence (automatically escaped) xml = Builder::XmlMarkup.new xml.cdata!("Content with ]]> embedded") xml.target! #=> " embedded]]>" ``` -------------------------------- ### Generate XML Comments in Ruby Source: https://github.com/jimweirich/builder/blob/master/README.md Demonstrates how to add XML comments to the generated markup using the `comment!` method. This is useful for adding explanatory notes within the XML structure. ```ruby xml_markup.comment! "This is a comment" #=> ``` -------------------------------- ### Method-Based Tag Generation Source: https://context7.com/jimweirich/builder/llms.txt Illustrates how Builder automatically converts Ruby method calls into XML tags, including simple tags, tags with attributes, and nested structures using blocks. ```APIDOC ## Method-Based Tag Generation ### Description Any method called on the builder that isn't a reserved method is automatically converted to an XML tag. Pass content as the first argument, attributes as a hash, and nest elements using blocks. ### Method `builder_instance.tag_name(content = nil, attributes = {}, &block)` ### Parameters - **tag_name** (Symbol or String) - The name of the XML tag to create. - **content** (String, optional) - The text content of the tag. - **attributes** (Hash, optional) - A hash of attributes for the tag. - **block** (Proc, optional) - A block to define nested elements. ### Request Example ```ruby require 'builder' xml = Builder::XmlMarkup.new(:indent => 2) # Simple tags xml.simple #=> "" xml = Builder::XmlMarkup.new xml.greeting("Hello") puts xml.target! #=> "Hello" # Tags with attributes xml = Builder::XmlMarkup.new xml.a("Click here", :href => "http://example.com", :target => "_blank") puts xml.target! #=> "Click here" # Nested tags with block syntax xml = Builder::XmlMarkup.new(:indent => 2) xml.html do |x| x.head do x.title("My Page") x.meta(:charset => "UTF-8") end x.body do x.h1("Welcome") x.p("This is a paragraph.") x.ul do x.li("Item 1") x.li("Item 2") x.li("Item 3") end end end puts xml.target! # Output: # # # My Page # # # #

Welcome

#

This is a paragraph.

#
    #
  • Item 1
  • #
  • Item 2
  • #
  • Item 3
  • #
# # ``` ### Response #### Success Response (200) - **String**: The generated XML markup. #### Response Example ```json { "example": "\n \n My Page\n \n \n \n

Welcome

\n

This is a paragraph.

\n
    \n
  • Item 1
  • \n
  • Item 2
  • \n
  • Item 3
  • \n
\n \n" } ``` ``` -------------------------------- ### Builder::XmlEvents SAX-like Generation Source: https://context7.com/jimweirich/builder/llms.txt Explains how to use XmlEvents to generate SAX-style events instead of direct string output, allowing for custom processing logic. ```APIDOC ## Builder::XmlEvents ### Description Creates SAX-like XML events. Events are dispatched to a handler object that must implement `start_tag`, `end_tag`, and `text` methods. ### Method N/A (Event-driven) ### Parameters - **target** (Object) - The handler object that receives the events. ### Response - **events** (Array) - A sequence of event objects containing type, tag, and attribute data. ``` -------------------------------- ### Generate XML Tags using Method-Based Syntax Source: https://context7.com/jimweirich/builder/llms.txt Leverages Ruby's method_missing to convert method calls into XML tags. Content can be passed as the first argument, attributes as a hash, and nested elements can be defined using block syntax. ```ruby require 'builder' xml = Builder::XmlMarkup.new(:indent => 2) # Simple tags xml.simple #=> "" xml = Builder::XmlMarkup.new xml.greeting("Hello") xml.target! #=> "Hello" # Tags with attributes xml = Builder::XmlMarkup.new xml.a("Click here", :href => "http://example.com", :target => "_blank") xml.target! #=> "Click here" # Nested tags with block syntax xml = Builder::XmlMarkup.new(:indent => 2) xml.html do |x| x.head do x.title("My Page") x.meta(:charset => "UTF-8") end x.body do x.h1("Welcome") x.p("This is a paragraph.") x.ul do x.li("Item 1") x.li("Item 2") x.li("Item 3") end end end puts xml.target! # Output: # # # My Page # # # #

Welcome

#

This is a paragraph.

#
    #
  • Item 1
  • #
  • Item 2
  • #
  • Item 3
  • #
# # ``` -------------------------------- ### Create XML Elements with Dynamic Names using tag! Source: https://context7.com/jimweirich/builder/llms.txt Generates an XML tag with a dynamic name, useful for tag names with special characters or runtime-determined names. It accepts text content, attributes, and a block for nested elements. ```ruby require 'builder' xml = Builder::XmlMarkup.new # Tag with special characters in name xml.tag!("SOAP:Envelope") { |x| x.tag!("SOAP:Body", "content") } xml.target! #=> "content" # Tag with attributes and text xml = Builder::XmlMarkup.new xml.tag!("custom-element", "Hello", :id => 123, :class => "highlight") xml.target! #=> "Hello" # Dynamic tag names from variables xml = Builder::XmlMarkup.new(:indent => 2) tag_name = "dynamic-tag" attributes = { :version => "1.0", :type => "custom" } xml.tag!(tag_name, attributes) do |x| x.tag!("sub-item", "Value 1") x.tag!("sub-item", "Value 2") end xml.target! #=> "\n Value 1\n Value 2\n\n" # Tag with Ruby reserved words xml = Builder::XmlMarkup.new xml.tag!("class", :id => 1) { |x| x.tag!("loop", "content") } xml.target! #=> "content" ``` -------------------------------- ### Appending Unescaped Content with Builder's << Operator Source: https://context7.com/jimweirich/builder/llms.txt Demonstrates using the `<<` operator to append raw, unescaped content to the XML output. This is useful for inserting pre-formatted XML snippets or combining output from multiple Builder instances without further escaping. ```ruby require 'builder' # Insert raw XML content xml = Builder::XmlMarkup.new xml.div do |x| x << "Pre-formatted HTML" x.p("Normal content") end xml.target! #=> "
Pre-formatted HTML

Normal content

" # Stacking builders (using one builder as target for another) outer = Builder::XmlMarkup.new(:indent => 2) inner = Builder::XmlMarkup.new(:target => outer) outer.container do inner.item("First") inner.item("Second") end puts outer.target! # Output: # # First # Second # # Combining output from multiple sources xml = Builder::XmlMarkup.new header_xml = "
Report
" footer_xml = "
2024
" xml.document do |x| x << header_xml x.body { x.content("Main content here") } x << footer_xml end xml.target! #=> "
Report
Main content here
2024
" ``` -------------------------------- ### Generating SAX-like XML Events Source: https://context7.com/jimweirich/builder/llms.txt Uses Builder::XmlEvents to generate XML structures as a stream of events rather than a single string. This requires a handler object that implements start_tag, end_tag, and text methods. ```ruby require 'builder' class XmlEventHandler attr_reader :events def initialize; @events = []; end def start_tag(tag, attrs); @events << { type: :start, tag: tag, attrs: attrs }; end def end_tag(tag); @events << { type: :end, tag: tag }; end def text(content); @events << { type: :text, content: content }; end end handler = XmlEventHandler.new xe = Builder::XmlEvents.new(:target => handler) xe.person(:id => 1) do |x| x.name("John Doe") x.email("john@example.com") end ``` -------------------------------- ### comment! - Insert XML Comments Source: https://context7.com/jimweirich/builder/llms.txt Inserts an XML comment into the markup, automatically wrapping the content in markers. ```APIDOC ## comment! (XML Comment) ### Description Inserts an XML comment. The content is properly formatted with indentation if configured. ### Parameters - **text** (String) - Required - The text content of the comment. ### Request Example xml.comment!("Database configuration") ### Response - **Output** (String) - "" ``` -------------------------------- ### declare! - DTD and Entity Declarations Source: https://context7.com/jimweirich/builder/llms.txt Inserts XML declarations for DTDs, elements, entities, and document type definitions. ```APIDOC ## declare! (DTD Declaration) ### Description Inserts DTD declarations. Symbols are inserted without quotes, strings with double quotes. ### Parameters - **type** (Symbol) - Required - The declaration type (e.g., :DOCTYPE, :ELEMENT). - **args** (Array) - Optional - Additional arguments for the declaration. ### Request Example xml.declare!(:DOCTYPE, :html) ### Response - **Output** (String) - "" ``` -------------------------------- ### Managing XML Attribute Escaping in Builder Source: https://context7.com/jimweirich/builder/llms.txt Demonstrates how Builder handles attribute escaping. String values are automatically escaped, while symbols are treated as raw text, allowing for entity references or unescaped content. ```ruby xml = Builder::XmlMarkup.new xml.company(:name => "Smith & Sons", :slogan => "Quality \"Guaranteed\"") xml.target! xml = Builder::XmlMarkup.new xml.link(:href => :"&baseurl;/page.html", :title => "Normal \"escaping\"") xml.target! xml = Builder::XmlMarkup.new xml.sample( :escaped => "AT&T", :unescaped => :"M&M" ) xml.target! xml = Builder::XmlMarkup.new xml.text(:value => "Line 1\nLine 2\rLine 3") xml.target! ``` -------------------------------- ### Inserting Escaped Text with Builder's text! Method Source: https://context7.com/jimweirich/builder/llms.txt Shows how to insert plain text content into an XML structure using the `text!` method. This method automatically escapes XML special characters to ensure valid markup. It's useful for inserting text that might contain characters like '<', '>', or '&'. ```ruby require 'builder' # Basic text insertion with escaping xml = Builder::XmlMarkup.new xml.div do |x| x.text!("Price: $10 < $20 & ") x.strong("save money!") end xml.target! #=> "
Price: $10 < $20 & save money!
" # Mixed content with text and elements xml = Builder::XmlMarkup.new(:indent => 2) xml.p do |x| x.text!("Click ") x.a("here", :href => "#") x.text!(" to continue or ") x.a("cancel", :href => "/cancel") x.text!(".") end xml.target! #=> "

\n Click here\n to continue or cancel\n .\n

\n" # Building inline formatted text xml = Builder::XmlMarkup.new xml.span do |x| x.text!("The ") x.em("quick") x.text!(" brown ") x.strong("fox") x.text!(" jumps over the lazy dog.") end xml.target! #=> "The quick brown fox jumps over the lazy dog." ``` -------------------------------- ### Builder Gem Attribute Escaping Source: https://context7.com/jimweirich/builder/llms.txt Illustrates how Builder automatically escapes string attribute values to ensure valid XML. It also shows how to use symbols for attribute values that should not be escaped, such as XML entity references. ```ruby require 'builder' # String attribute values are automatically escaped. # Use symbols for attribute values that should remain unescaped (e.g., entity references). xml = Builder::XmlMarkup.new xml.a("Click here", :href => "http://example.com?q=a&b=c", :title => "Link with < & >") puts xml.target! #=> "Click here" ``` -------------------------------- ### Attribute Escaping Rules Source: https://github.com/jimweirich/builder/blob/master/README.md Details how attribute values are handled in Builder 2.0.0, specifically regarding automatic escaping of strings versus symbols. ```APIDOC ## PUT /Builder::XmlMarkup/Attributes ### Description Configures how attributes are rendered in XML. String values are automatically escaped, while Symbol values are rendered as-is. ### Method PUT ### Parameters #### Request Body - **attributes** (Hash) - Required - Key-value pairs representing XML attributes. ### Request Example ```ruby xml.sample(:escaped => "This&That", :unescaped => :"Here&There") ``` ### Response #### Success Response (200) - **output** (String) - The resulting XML tag with escaped/unescaped attributes. #### Response Example ```xml ``` ``` -------------------------------- ### Control attribute escaping in XML Source: https://github.com/jimweirich/builder/blob/master/README.md Explains how Builder handles attribute escaping. String values are automatically escaped, while Symbol values remain unescaped. ```ruby xml = Builder::XmlMarkup.new xml.sample(:escaped=>"This&That", :unescaped=>:"Here&There") xml.target! # => ``` -------------------------------- ### cdata! - Insert CDATA Sections Source: https://context7.com/jimweirich/builder/llms.txt Inserts a CDATA section for content that should not be parsed as XML, such as scripts or raw text. ```APIDOC ## cdata! (CDATA Section) ### Description Inserts a CDATA section. Automatically handles escaping of the CDATA close sequence (]]>). ### Parameters - **content** (String) - Required - The raw content to be wrapped in CDATA. ### Request Example xml.cdata!("function test() { return true; }") ### Response - **Output** (String) - "" ``` -------------------------------- ### Escape XML Attribute Values in Ruby Source: https://github.com/jimweirich/builder/blob/master/README.md Details how Builder automatically escapes string attribute values to prevent XML injection issues. Using symbols for attribute values bypasses this escaping mechanism. ```ruby xml = Builder::XmlMarkup.new xml.sample(:escaped=>"This&That", :unescaped=>:"Here&There") xml.target! => ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.