0

Im using Rails 3 to_xml on a Model with a few options like include, except and methods. So this is not my first time using to_xml.

I'm doing something like this:

to_xml(include: {
  order: {
    methods: [:my_avg],
    except:  [:this_attr, :and_this_attr ]
  },
  customer: {}
})

The XML result:

<?xml version="1.0" encoding="UTF-8"?>
<my-model>
  <attr1 type="integer">12</attr1>
  <attr2 type="integer">12</attr2>
  <order>
    <name>foo</name>
    <desc>bar</desc>
    <my-avg>
      <avg type="integer">123</avg>
      <foo>ok</foo>
    </my-avg>
  </order>
  <updated-at type="datetime">2014-04-14T11:16:56-03:00</updated-at>
</my-model>

But now I want to change the xml encoding ISO_8859_1 instead of utf8.

I haven't seen an encoding option on ActiveRecord::Serialization module.

If I simply add one encoding option it creates a XML attribute instead of changing the encoding that results on this XML:

<?xml version="1.0" encoding="UTF-8"?>
<my-model>
  <attr1 type="integer" encoding="ISO-8859-1">12</attr1>
  <attr2 type="integer" encoding="ISO-8859-1">12</attr2>
  <order>
    <name>foo</name>
    <desc>bar</desc>
    <my-avg>
      <avg type="integer">123</avg>
      <foo>ok</foo>
    </my-avg>
  </order>
  <updated-at type="datetime">2014-04-14T11:16:56-03:00</updated-at>
</my-model>

Is there a way to specify the encoding using ActiveRecord's to_xml?

AndreDurao
  • 5,600
  • 7
  • 41
  • 61

1 Answers1

0

you may override to_xml in your Model & specify encoding. something like this could work:

class ModelName < ActiveRecord::Base
  def to_xml(options = {})
    require 'builder'
    options[:indent] ||= 2
    xml = options[:builder] ||= ::Builder::XmlMarkup.new(indent: options[:indent])
    xml.instruct! :xml, :version=>"1.0", :encoding => "ISO-8859-1"
    xml.level_one do
      xml.tag!(:second_level, 'content')
    end
  end
end
CuriousMind
  • 33,537
  • 28
  • 98
  • 137
  • It returns a rightfully encoded XML, but it did overwrite the default behavior. So the content is only: " content " – AndreDurao Apr 14 '14 at 16:23
  • Yes, you have to implement that yourself. Because it seems rails by default doesn't allow you override encoding, so you have to monkey-patch or implement it yourself. to take some inspiration, [here is how rails does it](https://github.com/rails/rails/blob/3-2-stable/activemodel/lib/active_model/serializers/xml.rb#L74-L97) – CuriousMind Apr 14 '14 at 20:45