jbuilder的set!方法重构接口

来源:互联网 发布:淘宝上买处方药打电话 编辑:程序博客网 时间:2024/05/02 20:46


https://github.com/rails/jbuilder  的set!方法重构接口,

因为grape没法使用 jBuilder 的缓存,所以直接用 Rails 写 API



(1)多个图片

images: {  poster: {    url: "http://r4.ykimg.com/0510000057CD17166714C04FDC0628CE",    md5: "ee63b0a11cb1e39331d5ce11d38fceec"},  right_top_corner: {    url: "http://r1.ykimg.com/0510000057CEA19C6714C063660BEB44",    md5: "e50d520de494538d4633086d46845a81"  }},


原来的方法为


 json.images do    component.pictures.each do |p|      if p.name == 'poster'        json.poster do          json.url "http://r#{rand(4) + 1}.xxx.com/#{p.url}"          json.md5 p.md5        end      end      if p.name == 'icon'        json.icon do          json.url "http://r#{rand(4) + 1}.xxx.com/#{p.url}"          json.md5 p.md5        end      end      if p.name == 'background'        json.background do          json.url "http://r#{rand(4) + 1}.xxx.com/#{p.url}"          json.md5 p.md5        end      end  end end


精简后为

  json.images do    component.pictures.each do |p|       json.set! p.name do        json.set! :url, "http://r#{rand(4) + 1}.ykimg.com/#{p.url}"        json.set! :md5, p.md5      end     end   end 


(2)hints 是一个 hash,遍历 Hash 的文档 http://ruby-doc.org/core-2.3.1/Hash.html#method-i-each

hint: {  left: "left",  right: "111"},


精简前

  json.hint do    if component.hints.key?("left")      json.left component.hints["left"]    end     if component.hints.key?("center")      json.center component.hints["center"]    end     if component.hints.key?("right")      json.right component.hints["right"]    end   end

精简后

  json.hint do    component.hints.each do |key,value|      json.set! key, value    end  end





0 0