2012-10-05 50 views
2

我想將此.json.rabl視圖轉換爲.json.erb,並且由於im非常新,所以我正在尋找實現此目標的方向。什麼是最好的方式去做這件事? 將Rabl轉換爲Erb json視圖

object @perform 
attributes :id => :team_id 
attributes :perform_id 
node(:fb_user_id) {|x| x.user.fb_user_id.to_s} 
node(:first_name) {|x| x.user.first_name} 
node(:last_name) {|x| x.user.last_name} 
attributes :level, :jersey, :height, :weight, :positions 
node(:stat_source) {|x| Stat::SOURCES.key(x.stat_source)}

if [email protected] node({}, :if => lambda{ |m| @event.present? }) do |x| { mvp_votes: Vote.player_vote_count(@event.id, x.id) } end end

if [email protected] && (@_options[:event] || @event) node :stats do |perform| Hash[*perform.source_stats.where(event_id: (@_options[:event].try(:id) || @event.id)).map{|x|[x.name, x.value]}.flatten] end end

回答

3

Erb與模板語言(如Rabl)相反 - 您創建您想要的json,然後用erb插入值,而不是像在rabl中那樣使用代碼定義結構。

在周圍與<%%文本ERB>表示一些紅寶石代碼(用於分配,循環等):

<% x = "output" %> 

和<%=%>(NB =號)表示紅寶石代碼(任何代碼)將通過調用to_s輸出到模板:

<%= x.to_json %> 

任何未被這些符號包圍的東西都會完全按照原樣輸出。

所以你應該可以用假值創建你想要的json,然後把相關ruby代碼的調用放到運行時得到真實值。例如這樣的片段(不熟悉Rabl的這樣的JSON格式可能需要調整):

[{ "perform" : 
    { 
    "id" : <%= @perform.team_id %>, 
    "user" : <%= @perform.perform_id %>, 
    ... 

    } 
}] 

<% if [email protected] %> 
    <% node({}, :if => lambda{ |m| @event.present? }) do |x| %> 
    { 
    mvp_votes: <%= Vote.player_vote_count(@event.id, x.id) %> 
    } 
    <% end %> 
<% end %> 

對於那些工整地映射到JSON作爲哈希,例如,你也可以考慮創建to_json方法,而不是解僱他們了對象在像這樣的模板中,但對於像這樣的複雜結構而沒有乾淨的映射,模板可能是最好的。

我想在一個名爲xx.json.erb(純json)的文件中使用json,然後開始使用erb插入值。

0

也許這不是一個確切問題的答案,但在軌道中執行JSON視圖的認可方式是使用jbuilder

JBuilder的API與RABL的API非常相似,但它是由同一個Rails核心團隊完成的,所以它與所有內部組件集成在一起,比如緩存助手(將來還有緩存依賴),partials等等。

https://github.com/rails/jbuilder