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?
-
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) endUpdate:
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 endThen in your models:
class MyModel < ActiveRecord::Base include DefaultXml endDrew 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 endNext, 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 endIt 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