Class: Acter::Result

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/acter/result.rb

Constant Summary collapse

DEFAULT_RENDER_OPTIONS =
{
  show_body: true,
  show_headers: false,
  show_status: true,
  color: :tty?,
  theme: "monokai",
}

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(response) ⇒ Result

Returns a new instance of Result.



18
19
20
# File 'lib/acter/result.rb', line 18

def initialize(response)
  @response = response
end

Instance Attribute Details

#responseObject (readonly)

Returns the value of attribute response.



22
23
24
# File 'lib/acter/result.rb', line 22

def response
  @response
end

Instance Method Details

#render(options = nil) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/acter/result.rb', line 25

def render(options = nil)
  options = DEFAULT_RENDER_OPTIONS.merge(Hash(options))
  if block_given?
    more_options = yield response
    options.merge!(Hash(more_options))
  end

  colorize = options[:color] && (options[:color] != :tty? || $>.tty?)

  StringIO.open do |s|
    if options[:show_status]
      if colorize
        s.puts Term::ANSIColor.bold(response.status)
      else
        s.puts response.status
      end
    end
    if options[:show_headers]
      response.headers.each(&s.method(:puts))
    end
    if options[:show_body]
      s.puts
      if colorize
        lexer = response.body_is_json? ? Rouge::Lexers::JSON : Rouge::Lexers::HTML
        s.puts Rouge::Formatters::Terminal256.format(lexer.new.lex(response.body), theme: options[:theme])
      else
        s.puts response.body
      end
    end
    s.string
  end
end