在变量中捕获 json.builder 数据

问题描述

我在控制器文件中有一个函数,我们在函数末尾渲染响应,如下所示:

render_response(template: 'index')

render_response 是一个单独的帮助文件中的自定义函数,定义如下:

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 

我想在控制器文件中的一个变量(比如 index.json.builder )中捕获来自 json_data 的整个 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,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\"}}}"

据说将数据从视图渲染回控制器并不是我建议的事情,至少可以说这不是一个非常简单和轻松的过程(考虑到 Rails 应用程序的全部目的是使您的应用程序将数据转换为视图,然后转换为您的浏览器,这与您提出的要求相反)

我确实认为这里更好的方法是将 JSON 构建拉入类或模型或方法中,然后在控制器和视图中使用该方法


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