轻松的方式可以打印到视图或闪存?

时间:2017-02-10 05:14:47

标签: html ruby-on-rails pretty-print developer-tools flash-message

我喜欢能够轻松地将数据结构打印到标准输出中,像pretty-print这样的工具非常适合:

[8] pry(main)> foo
=> {"utf8"=>"", "authenticity_token"=>"0G0OwiWMK3CRmEdOlmxgNA5VrIIm7/iHg21AOLaSywEPnDGHTtGLcLjSATY7BN5lzucIrdCwbv9M+Nw++2tuYg==", "q"=>"foobar", "commit"=>"Some submit button", "controller"=>"statics", "action"=>"create"}
[9] pry(main)> p foo
{"utf8"=>"", "authenticity_token"=>"0G0OwiWMK3CRmEdOlmxgNA5VrIIm7/iHg21AOLaSywEPnDGHTtGLcLjSATY7BN5lzucIrdCwbv9M+Nw++2tuYg==", "q"=>"foobar", "commit"=>"Some submit button", "controller"=>"statics", "action"=>"create"}
=> {"utf8"=>"", "authenticity_token"=>"0G0OwiWMK3CRmEdOlmxgNA5VrIIm7/iHg21AOLaSywEPnDGHTtGLcLjSATY7BN5lzucIrdCwbv9M+Nw++2tuYg==", "q"=>"foobar", "commit"=>"Some submit button", "controller"=>"statics", "action"=>"create"}
[10] pry(main)> pp foo
{"utf8"=>"",
 "authenticity_token"=>
  "0G0OwiWMK3CRmEdOlmxgNA5VrIIm7/iHg21AOLaSywEPnDGHTtGLcLjSATY7BN5lzucIrdCwbv9M+Nw++2tuYg==",
 "q"=>"foobar",
 "commit"=>"Some submit button",
 "controller"=>"statics",
 "action"=>"create"}
=> {"utf8"=>"", "authenticity_token"=>"0G0OwiWMK3CRmEdOlmxgNA5VrIIm7/iHg21AOLaSywEPnDGHTtGLcLjSATY7BN5lzucIrdCwbv9M+Nw++2tuYg==", "q"=>"foobar", "commit"=>"Some submit button", "controller"=>"statics", "action"=>"create"}

是否有一些工具可以让我在视图或闪光灯中打印出漂亮的东西?例如,如果我在Statics#create

def create
  flash[:notice] = params.inspect
  redirect_to statics_url
end

然后渲染的html看起来像:

enter image description here

是否有一种简单的方法可以打印params,以便它们显示在我的视图或闪光灯中?

我尝试过使用pretty_inspect

application.html.erb:

<body>
  <% if flash[:notice] %>
    <%= render plain: flash[:notice] %>
  <% end %>
  <%= yield %>
</body>

statics_controller.rb:

def create
  flash[:notice] = params.pretty_inspect 
  redirect_to statics_url
end

但它不起作用:

enter image description here

使用debug也会呈现非漂亮的哈希:

<body>
  <%= debug(params) if Rails.env.development? %>
  <%= debug(flash[:notice]) if Rails.env.development? %>
  <%#= debug(@collection) if Rails.env.development? %>
  <%#= debug(current_user) if Rails.env.development? %>
  <%= yield %>
</body>

enter image description here

修改

有没有比gsub bing更好的方法?:

<%= debug(flash[:notice].inspect.gsub(',', ",\n").gsub('\\','')) if Rails.env.development? %>

enter image description here

2 个答案:

答案 0 :(得分:1)

您可以使用JSON.pretty_generate

<body>
  <pre>
    <%= preserve do %>
        <%= JSON.pretty_generate(params) if Rails.env.development? %>
        <%= JSON.pretty_generate(flash[:notice]) if Rails.env.development?%>
    <% end %>
  </pre>
  <%= yield %>
</body>

答案 1 :(得分:0)

您可以在<%= debug(params) if Rails.env.development? %>文件中添加application.html.erb之类的内容

例如,如果您想查看视图中控制器和控制器中特定变量的内容,您可以定义所需的这类语句的数量:

<%= debug(params) if Rails.env.development? %>
<%= debug(@collection) if Rails.env.development? %>
<%= debug(current_user) if Rails.env.development? %>

对于漂亮的输出,你应该参与bootstrap - 请检查this link