jbuilder的set!方法重构接口


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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值