class Plz::ResponseRenderer
Public Class Methods
call(*args)
click to toggle source
Shortcut for call
method
# File lib/plz/response_renderer.rb, line 4 def self.call(*args) new(*args).call end
new(status: nil, headers: nil, body: nil, response_header: nil, response_body: nil, color: nil)
click to toggle source
@param status [Fixnum] Status code @param headers [Hash] Response header fields @param body [Array, Hash] JSON decoded response body @param response_header [true, false] Flag to show response header @param response_body [true, false] Flag to show response body @param color [true, false] Flag to color response body
# File lib/plz/response_renderer.rb, line 14 def initialize(status: nil, headers: nil, body: nil, response_header: nil, response_body: nil, color: nil) @status = status @headers = headers @body = body @show_response_header = response_header @show_response_body = response_body @color_response = color end
Public Instance Methods
call()
click to toggle source
Renders response with given options @return [String] Rendered output
# File lib/plz/response_renderer.rb, line 25 def call template % { status: status, headers: headers, body: body, } end
Private Instance Methods
Rainbow(str)
click to toggle source
Overridden to disable coloring
Calls superclass method
# File lib/plz/response_renderer.rb, line 89 def Rainbow(str) if @color_response super else Rainbow::NullPresenter.new(str.to_s) end end
body()
click to toggle source
@return [String]
# File lib/plz/response_renderer.rb, line 72 def body if @color_response Rouge::Formatters::Terminal256.format( Rouge::Lexers::Javascript.new.lex(plain_body), theme: "github" ) else plain_body end end
headers()
click to toggle source
@return [String] @example
headers #=> ["Content-Type: application/json"]
# File lib/plz/response_renderer.rb, line 50 def headers @headers.sort_by do |key, value| key end.map do |key, value| "%{key}: %{value}" % { key: Rainbow(key.split("-").map(&:camelize).join("-")).underline, value: Rainbow(value).green, } end.join("\n") end
plain_body()
click to toggle source
@return [String] Pretty-printed JSON body
# File lib/plz/response_renderer.rb, line 84 def plain_body JSON.pretty_generate(@body) + "\n" end
status()
click to toggle source
@return [String]
# File lib/plz/response_renderer.rb, line 62 def status Rainbow("#{@status} #{status_in_words}").bright end
status_in_words()
click to toggle source
@return [String] Words for its status code
# File lib/plz/response_renderer.rb, line 67 def status_in_words Rack::Utils::HTTP_STATUS_CODES[@status] end
template()
click to toggle source
@return [String] Template for embedding variables, changing by options
# File lib/plz/response_renderer.rb, line 36 def template str = "" str << <<-EOS.strip_heredoc if @show_response_header HTTP/1.1 %{status} %{headers} EOS str << "\n" if @show_response_header && @show_response_body str << "%{body}" if @show_response_body str end