如何將一個參數傳遞給#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