开发者

Using a template to generate json to send to web service

I am generating some json to send to a web service.

Currently I am creating a hash, loading it with the data and then calling to_json to generate the json string to send.

But I figure it would be much cleaner and more rails like if I could use a template in a .erb 开发者_C百科file to generate the json for me.

All the info I can find on erb files use it to create data to send back to the client. I dont want to do this, I am the client here!

How can I do this?


ERB template engine is something you can use without Rails, actually.

require 'erb'

x = 42
template = ERB.new <<-EOF
  The value of x is: <%= x %>
EOF
puts template.result(binding)

In your case you can use a template like

{ foo: <%= model.foo.inspect %>, bar: <%= model.bar.inspect %> }

Store it in a .erb file, read the contents with File.open and then pass it to ERB.new, like in the example.

More info here: http://ruby-doc.org/stdlib/libdoc/erb/rdoc/classes/ERB.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜