Dasherizing Builder::XmlMarkup in Rails

October 29, 2008 | rails, ruby, xml

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:


# Creates a Builder::Markup implementation that dasherizes all element and attribute names
# Use this just like you would Builder::XmlMarkup
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

end

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

Enjoy!

  1. One Response to “Dasherizing Builder::XmlMarkup in Rails”

  2. Adam you kick ass as always. Thanks for solving this issue!

    By Stephen Orth on Oct 29, 2008

Post a Comment