如何将一个参数传递给#to_xml?你如何将参数传递给#to_xml?
@object.to_xml(:methods => [:a_method_with_args])
有没有办法做到这一点?什么是正确的语法?
谢谢。
如何将一个参数传递给#to_xml?你如何将参数传递给#to_xml?
@object.to_xml(:methods => [:a_method_with_args])
有没有办法做到这一点?什么是正确的语法?
谢谢。
to_xml应该表达你模型的状态。因此它不应该需要任何外部“位置”论点。如果这真的是你需要的东西,它看起来像你需要一个'给我一个xml表示我的模型,当位置X'。我想你可以只添加一个“set_default_location”到模型,改变price_points_for_location有对参数的默认值:
attr_writer :default_location
def price_points_for_location(location = @default_location)
...
end
你可以尝试重新定义to_xml方法类似
def to_xml(location)
# do your stuff
super()
end
但不肯定它会很好地工作。另一个选项是创建一些新的XML视图的方法为您的模型,如:
def as_xml(location)
self.price_points_for_location(location)
self.to_xml
end
感谢您的答案,它们看起来像不错的选择。我最终做的是使用proc。我意识到我可以使用to_xml使用procs,但似乎在迭代多个对象时无法访问数组中的当前对象。为了解决这个问题,我做了这样的事情:
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])
你可以扩展一下你想做什么?我会说创建一个模型方法会起作用。 – Yaraher 2009-09-12 16:57:46
我试图通过它存在于我的模型中的方法,但它需要一个参数,因为它取决于不同的模型。 该方法通常被称为像这样:@ item.price_points_for_location(location) 我不知道如何将位置参数传递给方法。其他的做法也可以,但我不知道那会是什么。 – Zef 2009-09-12 18:18:08