Sha256: d7bb1bd2dde79f016bdde7cc4310088453f3f36b48981631a49ee32ce4ee73e2

Contents?: true

Size: 1.65 KB

Versions: 11

Compression:

Stored size: 1.65 KB

Contents

require_relative "inline_labeler"
require_relative "outline_labeler"

module CutePrint
  # @api private
  class Labeler

    def self.label(format, width, label, value)
      new(format, width, label, value).labeled
    end

    def initialize(format, width, label, value)
      @format = format
      @width = width
      @label = label
      @value = value
    end

    def labeled
      # Optimization: Avoid the computation of "outlined", and the
      # elaborate comparison, in many cases.
      return outlined if outlined_fits_on_one_line?
      inlined_fits = lines_fit_horizontally?(inlined)
      outlined_fits = lines_fit_horizontally?(outlined)
      if inlined_fits && outlined_fits
        [inlined, outlined].min_by do |lines|
          [
            lines.size,
            lines.equal?(outlined) ? 0 : 1,
          ]
        end
      elsif inlined_fits && !outlined_fits
        inlined
      elsif !inlined_fits && outlined_fits
        outlined
      else # neither fits
        [inlined, outlined].min_by do |lines|
          [
            lines.map(&:size).min,
            lines.size,
          ]
        end
      end
    end

    private

    def lines_fit_horizontally?(lines)
      lines.all? do |line|
        line_fits_horizontally?(line)
      end
    end

    def line_fits_horizontally?(line)
      line.chomp.size <= @width
    end

    def outlined_fits_on_one_line?
      outlined.size == 1 && line_fits_horizontally?(outlined.first)
    end

    def outlined
      @outlined ||= OutlineLabeler.label(@format, @width, @label, @value)
    end

    def inlined
      @inlined ||= InlineLabeler.label(@format, @width, @label, @value)
    end
    
  end
end

Version data entries

11 entries across 11 versions & 1 rubygems

Version Path
cute_print-1.4.0 lib/cute_print/labeler.rb
cute_print-1.3.0 lib/cute_print/labeler.rb
cute_print-1.2.0 lib/cute_print/labeler.rb
cute_print-1.1.4 lib/cute_print/labeler.rb
cute_print-1.1.3 lib/cute_print/labeler.rb
cute_print-1.1.2 lib/cute_print/labeler.rb
cute_print-1.1.1 lib/cute_print/labeler.rb
cute_print-1.1.0 lib/cute_print/labeler.rb
cute_print-1.0.1 lib/cute_print/labeler.rb
cute_print-1.0.0 lib/cute_print/labeler.rb
cute_print-0.4.0 lib/cute_print/labeler.rb