簡體   English   中英

在變量中捕獲 json.builder 數據

[英]Capture json.builder data in a variable

我在 controller 文件中有一個 function 文件,我們在 function 的末尾呈現響應,如下所示:

render_response(template: 'index')

render_response 是一個自定義的 function 在一個單獨的幫助文件中,定義如下:

def render_response(options = {})
  options[:status] = build_status_code(options)
  response_json = {
    success: success_status(options[:status]),
    code: options[:status],
    data: build_data(options),
  }
  render json: response_json, status: options[:status]
end

此外,還有一個文件 index.json.builder 包含如下內容:

hash = { author: { name: "David" } }
json.post do
  json.title "Merge HOWTO"
  json.merge! hash
end 

我想在 controller 文件中的變量(比如說json_data )中捕獲來自index.json.builder的整個 JSON 。 但是,我無法找到它的語法或方法。
任何線索將不勝感激。

您可以嘗試使用 JBuilder 測試中的邏輯https://github.com/rails/jbuilder/blob/master/test/jbuilder_template_test.rb#L287-L311我能夠讓它在我的控制器/控制台中工作

def build_view(options = {})
    
    lookup_context = ActionView::LookupContext.new([ "app/views/homes/" ], {}, [""]) # REPLACE HERE YOUR VIEW OR PARTIAL DIRECTORY PATH
    controller = self

    view = if ActionView::Base.respond_to?(:with_empty_template_cache)
    ActionView::Base.with_empty_template_cache.new(lookup_context, options.fetch(:assigns, {}), controller)
    else
    ActionView::Base.new(lookup_context, options.fetch(:assigns, {}), controller)
    end

    def view.view_cache_dependencies; []; end

    view
end

result = build_view.render(partial: "show") # name of your partial or view
=> :build_view
  Rendered homes/_show.json.jbuilder (Duration: 0.6ms | Allocations: 174)
=> "{\"post\":{\"title\":\"Merge HOWTO\",\"author\":{\"name\":\"David\"}}}"

據說將視圖中的數據渲染回 controller 不是我建議的,至少可以說這不是一個非常簡單和輕松的過程(考慮到您的 rails 應用程序的全部目的是讓您的應用程序將數據轉換為然后查看您的瀏覽器,這與您詢問的路線相反)

I do think the better approach here is to pull the JSON building into a class or model or a method then use that method inside your controller and your view


def the_json_data_you_want
  hash = { author: { name: "David" } }
  Jbuilder.new do |json|
    json.post do
      json.title "Merge HOWTO"
      json.merge! hash
    end
  end
end

要檢索 JSON,您可以調用the_json_data_you_want.target!

irb(main):7:0> the_json_data_you_want.target!
=> "{\"post\":{\"title\":\"Merge HOWTO\",\"author\":{\"name\":\"David\"}}}"

然后你可以在你的控制器中使用它並將它傳遞給它將被渲染的視圖

這里有更多文檔https://github.com/rails/jbuilder

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM