Posted By

ctran on 01/29/08


Tagged

activerecord


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

webstic


to_xml patch with modules


 / Published in: Ruby
 

Fix the broken toxml when using with modules. Also limit to protectedattributes by default. This can be saved to config/initializers/toxmlpatch.rb

  1. # Fix the broken to_xml when using with modules. Also limit to protected_attributes by default.
  2. module ToXmlPatch
  3. module ActiveRecordFix
  4. def self.included(base)
  5. base.class_eval do
  6. alias_method_chain :to_xml, :fix
  7. end
  8. end
  9.  
  10. def to_xml_with_fix(options = {}, &block)
  11. # protect attributes registered with attr_protected
  12. default_except = self.class.protected_attributes()
  13. options[:except] = (options[:except] ? options[:except] + default_except : default_except)
  14.  
  15. # for models that are namespaced in Ruby module
  16. options[:root] ||= self.class.name.tableize.singularize.gsub(/\//, ':')
  17. to_xml_without_fix(options, &block)
  18. end
  19. end
  20.  
  21. module ArrayFix
  22. def self.included(base)
  23. base.class_eval do
  24. alias_method_chain :to_xml, :fix
  25. end
  26. end
  27.  
  28. def to_xml_with_fix(options = {})
  29. contained_class = self.first.class.name
  30. options[:root] ||= contained_class.tableize.gsub(/\//, ':') # for models that are namespaced in Ruby module
  31. options[:children] ||= contained_class.tableize.singularize.gsub(/\//, ':') # for models that are namespaced in Ruby module
  32. to_xml_without_fix(options)
  33. end
  34. end
  35. end
  36.  
  37. puts "Patching to_xml..."
  38. Array.send(:include, ToXmlPatch::ArrayFix)
  39. ActiveRecord::Base.send(:include, ToXmlPatch::ActiveRecordFix)

Report this snippet  

You need to login to post a comment.