views:

88

answers:

3

How can I pass a method with an argument to #to_xml?

@object.to_xml(:methods => [:a_method_with_args] )

Is there a way to do this? What is the correct syntax?

Thanks.

A: 

to_xml is supposed to express your model's state. and as such it shouldn't need any external 'location' arguments. if this is really what you need it looks like you need a 'give me an xml representation of my model when on location X'. I guess you can just add a 'set_default_location' to your model and change the price_points_for_location to have a default value for the argument:

attr_writer :default_location
def price_points_for_location(location = @default_location)
  ...
end
Vitaly Kushner
A: 

You could try redefining the to_xml method like

def to_xml(location)
   # do your stuff
   super()
end

But not sure it would work that well. Other option would be to create some new XML view method for your model, like:

def as_xml(location)
   self.price_points_for_location(location)
   self.to_xml
end
Yaraher
A: 

Thanks for the answers, they look like good options. What I actually ended up doing is using a proc. I was aware that I could use procs with to_xml, but it seems that you can't access the current object in the array when iterating over multiple objects. To get around this I did something like this:

price_points = @items.map { |item| item.price_points_for_location(location) }
price_point = Proc.new {|options| options[:builder].tag!('price_points', price_points.shift) }
@items.to_xml(:procs => [price_point])
Zef