Dasherizing Builder::XmlMarkup in Rails

by Adam Pearson
on 2008.10.29

Rails 2.x automatically dasherizes ActiveRecord inheritors when to_xml is called, but if you want to deal directly with Builder::XmlMarkup you have to go through some hoops to dasherize your element names.

I solved this problem today with a simple subclass. Here’s the code:

class DasherizingBuilder < Builder::XmlMarkup  
  
  def _start_tag(sym, attrs, end_too=false)  
    super(sym.to_s.dasherize, attrs, end_too)  
  end  
  
  def _end_tag(sym)  
    super(sym.to_s.dasherize)  
  end  
  
  def _insert_attributes(attrs, order=[])  
    return if attrs.nil?  
    new_order= []  
    order.each {|item| new_order << item.to_s.dasherize}  
  
    new_attrs = {}  
    attrs.each do |k,v|  
      new_attrs[k.to_s.dasherize] = v  
    end  
  
    super(new_attrs, new_order)  
  end  

Put it in your lib/ and just new up a new DasherizingBuilder to make <sad_clown> into <sad-clown>.

Enjoy!

» permalink