Sha256: 13fcb8355d63755ad8a51cced6e279de622a057fb9b4975b1f74a39d3bbcdb44

Contents?: true

Size: 1.37 KB

Versions: 4

Compression:

Stored size: 1.37 KB

Contents

require "forwardable"
require "rouge"
require "stringio"
require "term/ansicolor"

module Acter
  class Result
    extend Forwardable

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

    def initialize(response)
      @response = response
    end

    attr_reader :response
    def_delegator :@response, :success?

    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
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
acter-0.2.0 lib/acter/result.rb
acter-0.1.3 lib/acter/result.rb
acter-0.1.2 lib/acter/result.rb
acter-0.1.1 lib/acter/result.rb