模型to_api 不论什么xml格式还是json格式 ... no reply

2010-12-30 17:29

模型to_api 不论什么xml格式还是json格式 ... no reply

by Latest from ChinaonRails

at 2010-12-30 09:29:20

original http://feedproxy.google.com/~r/LatestFromChinaonrails/~3/kfzchzU_fRU/4736.html

https://github.com/atomicobject/to_api
A lightweight, format-agnostic API transformation gem.

http://spin.atomicobject.com/2010/12/28/to_api-simple-api-transformations

Models shouldn't know about formats. Controllers shouldn't know what attributes your domain objects have. It should be trivial to serve the same data in multiple formats.

Enter to_api. Instead of to_xml and as_json, simply implement to_api. Return an unformatted hash. Let the model understand the data. Let the controller understand the format. In Rails, the controller can simply call render :xml => model.to_api or render :json => model.to_api.

调用 to_api method
You'll get back a hash of arrays, hashes, strings, numbers, and nil. All of these are very easily converted to a format of your choice.

模型定义属性漏给某个API,模型说了算