Setting new default properties for to_xml serializer in Rails

In Rails, I am coding for a number of controllers to generate XML. Every time I pass multiple properties to to_xml, for example:

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

      

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

0


source to share


3 answers


Are you calling to_xml on a hash or an ActiveRecord model (or whatever)?

I don't want you to want it, but you can easily patch the to_xml monkey and override it to start with these parameters. I would suggest that you create a new to_default_xml method that just called to_xml with the parameters you want

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

      

Update:

Since you want to add this to multiple ActiveRecord models, you can do two things: open ActiveRecord :: base (which is a bit hacky and fragile), or create a module and import it into each 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

      

+3


source


I put together a plugin to handle default serialization parameters. 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 supports several serialization styles, which can be called like:

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

      

+1


source


Assuming you are talking about the AR to_xml method and depending on your needs you can get away with extending the AcitveRecord class by creating a file called: lib \ class_extensions.rb

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

      

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

require 'class_extensions'

      

Now you can use it like this (without having to include it in every model):

MyModel.to_xml_default

      

0


source







All Articles