Monday, March 7, 2011

setting new default properties for to_xml serializer in Rails

In Rails, I'm coding a series of controllers to generate XML. Each time I'm passing a number of properties in to to_xml like:

to_xml(:skip_types => true, :dasherize => false)

Is there a way I can set these as new default properties that will apply whenever to_xml is called in my app so that I don't have to repeat myself?

From stackoverflow
  • Are you calling to_xml on a hash or an ActiveRecord model (or something else)?

    I am not that you would want to, but you can easily monkey patch to_xml and redefine it to start with those parameters. I would suggest that you make a new method to_default_xml that simply called to_xml with the parameters you wanted

    def to_default_xml
      self.to_xml(:skip_types => true, :dasherize => false)
    end
    

    Update:

    Since you want to add this to a couple of ActiveRecord models you could do two things, open up ActiveRecord::base (which is a bit hackish and fragile) or create a module and import it into every model you want to use with it. A little more typing, but much cleaner code.

    I would put a class in lib/ that looks something like this:

    module DefaultXml
      def to_default_xml
        self.to_xml(:skip_types => true, :dasherize => false)
      end
    end
    

    Then in your models:

    class MyModel < ActiveRecord::Base
      include DefaultXml
    end
    
    Drew Dara-Abrams : Thanks! A wrapper method sounds like a good hack for me to use (for now). Given that I'm going to be calling this from multiple controllers (on ActiveRecord models), where would you recommend I put that code?
  • Assuming you're talking about AR's to_xml method and depending on your needs, you could get away with extending the AcitveRecord class by creating a file named: lib\class_extensions.rb

    class ActiveRecord::Base   
       def to_xml_default
          self.to_xml(:skip_types => true, :dasherize => false)
       end
    end
    

    Next, put this in an initializer, so that it's included when Rails starts up:

    require 'class_extensions'
    

    Now, you can use it as follows (w/o having to specifically include it in each model):

    MyModel.to_xml_default
    
  • I put together a plugin to handle default serialization options. Check it out at github.com/laserlemon/dry_serial/tree/master.

    class MyModel < ActiveRecord::Base
      dry_serial :skip_types => true, :dasherize => false
    end
    

    It also has support for multiple serialization styles that can be called like:

    @my_model.to_xml(:skinny)
    @my_model.to_xml(:fat)
    

0 comments:

Post a Comment