Return to Snippet

Revision: 4934
at January 29, 2008 22:38 by ctran


Initial Code
# 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)

Initial URL


Initial Description
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

Initial Title
to_xml patch with modules

Initial Tags


Initial Language
Ruby