/ Published in: Ruby
Fix the broken to_xml when using with modules. Also limit to protected_attributes by default. This can be saved to config/initializers/to_xml_patch.rb
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
# Fix the broken to_xml when using with modules. Also limit to protected_attributes by default. module ToXmlPatch module ActiveRecordFix def self.included(base) base.class_eval do alias_method_chain :to_xml, :fix end end def to_xml_with_fix(options = {}, &block) # protect attributes registered with attr_protected default_except = self.class.protected_attributes() options[:except] = (options[:except] ? options[:except] + default_except : default_except) # for models that are namespaced in Ruby module options[:root] ||= self.class.name.tableize.singularize.gsub(/\//, ':') to_xml_without_fix(options, &block) end end module ArrayFix def self.included(base) base.class_eval do alias_method_chain :to_xml, :fix end end def to_xml_with_fix(options = {}) contained_class = self.first.class.name options[:root] ||= contained_class.tableize.gsub(/\//, ':') # for models that are namespaced in Ruby module options[:children] ||= contained_class.tableize.singularize.gsub(/\//, ':') # for models that are namespaced in Ruby module to_xml_without_fix(options) end end end puts "Patching to_xml..." Array.send(:include, ToXmlPatch::ArrayFix) ActiveRecord::Base.send(:include, ToXmlPatch::ActiveRecordFix)