zoukankan      html  css  js  c++  java
  • Jbuilder(3300✨)

    https://github.com/rails/jbuilder 

    Jbuilder(3300✨)

    Jbuilder gives you a simple DSL for declaring JSON structures that beats manipulating giant hash structures. This is particularly helpful when the generation process is fraught with conditionals and loops. Here's a simple example:

    定义一个属性和结构的名字(动态的),使用 set! 方法

    json.set! :author do

      json.set! :name, 'David'

    end 

    #=> {"author": {"name": "David"}}

    合并一个已存在的hash,或者array到当前的content, 使用merge! 方法 

    hash = { author: { name: "David"} }

    json.post do

      json.title "Merge HOWTO"

      json.merge! hash 

    end 

    # => "post": { "title": "Merge HOWTO", "author": { "name": "David" } }

    可以使用ruby 语法, each,  比如案例中的: 

      # json.temperature @location.recordings.each do |record|
      #   json.temperature record.temp
      # end

    也可以使用array! , 同样是针对一对多的关联,只要是数组集合就行。

    方便的写法写:提取指定的属性: 

    json.array!  @location.recordings,  :temp, :status

    使用array!,可以输出array类型的资料 

    Jbuilder对象可以直接互相被嵌套到:

    比如建立1对多关联的表。

    company = Company.new("Dell", Person.new("John", 36))

    company.to_builder.target! 

    把对象变成jbuilder对象。

    # => {"name": "Dell", "president":{"name":"John", "age":58}} 

    可以用于ActionView template language。 如show.json.jbuilder.

    也可以用partials。 如views/comments/_comments.json.jbuilder, 然后设定一个局部变量comments :

    json.partial! 'comments/comments', comments: @message.comments 

    可以渲染partials集合:

    json.array! @posts, partial: 'posts/post', as: :post

    或者

    json.partials! partial: 'posts/post', collection: @posts, as: :post 

    《绿色框内的可以不写。》

    写法有多种 

    可以使用:local选项传入任意对象到局部模版:

    json.partials! "sub_template", locals: {user: :user}

    支持碎片缓存fragment caching: Rails.cache

    json.cache! ['v1', @person], expires_in: 10.minutes do
      json.extract! @person, :name, :age
    end
  • 相关阅读:
    sql中保留2位小数
    C# 操作字符串,在某些特定的字符后面或前面添加其它字符
    Windows Server 2008 R2中上传和下载文件
    winform中显示标题,点击打开链接
    正则表达式
    winform重绘
    js获取元素的页面坐标
    剑指offer-从上往下打印二叉树
    剑指offer-栈的压入、弹出序列
    剑指offer-包含min函数的栈
  • 原文地址:https://www.cnblogs.com/chentianwei/p/9321744.html
Copyright © 2011-2022 走看看