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
  • 相关阅读:
    You can’t access this shared folder because your organization’s security policies block unauthenticated guest access
    iOS 程序退出之后
    给网站得标签头加上小图标
    ios外界蓝牙适配
    JavaScript&jquery判断下载地址是否可用,同时判断浏览器是否禁用弹窗
    GCD初级使用
    find与xargs
    sed命令详解
    shell变量详解
    date命令详解
  • 原文地址:https://www.cnblogs.com/chentianwei/p/9321744.html
Copyright © 2011-2022 走看看