Sha256: 6c48c60344701db6c87c9098ef0a6e16a33c0ef96767684a3b7e192bce0c1ea8

Contents?: true

Size: 1.2 KB

Versions: 10

Compression:

Stored size: 1.2 KB

Contents

# frozen_string_literal: true

require "refinements/strings"

module Gemsmith
  module Gem
    # Formats single or multiple modules with correct, two-space indentation for templates.
    class ModuleFormatter
      using Refinements::Strings

      def initialize namespace
        @namespace = namespace
        @modules = namespace.split "::"
        @depth = namespace.scan("::").length
      end

      def render content
        "#{prefix}#{body content}#{suffix.chomp}"
      end

      private

      attr_reader :namespace, :modules, :depth

      def prefix
        modules.each.with_index.reduce "" do |result, (module_name, index)|
          result + "#{indentation index}module #{module_name}\n"
        end
      end

      def body content
        indent = indentation depth + 1

        content.sub(/\A\n/, "").split("\n").reduce "" do |body, line|
          next "#{body}\n" if line.blank?
          body + "#{indent}#{line.gsub(/^\s{2}/, "")}\n"
        end
      end

      def suffix
        modules.each.with_index.reduce "" do |result, (_, index)|
          result + "#{indentation depth - index}end\n"
        end
      end

      def indentation length
        "  " * length
      end
    end
  end
end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
gemsmith-9.6.0 lib/gemsmith/gem/module_formatter.rb
gemsmith-9.5.0 lib/gemsmith/gem/module_formatter.rb
gemsmith-9.4.0 lib/gemsmith/gem/module_formatter.rb
gemsmith-9.3.0 lib/gemsmith/gem/module_formatter.rb
gemsmith-9.2.0 lib/gemsmith/gem/module_formatter.rb
gemsmith-9.1.0 lib/gemsmith/gem/module_formatter.rb
gemsmith-9.0.0 lib/gemsmith/gem/module_formatter.rb
gemsmith-8.2.0 lib/gemsmith/gem/module_formatter.rb
gemsmith-8.1.0 lib/gemsmith/gem/module_formatter.rb
gemsmith-8.0.0 lib/gemsmith/gem/module_formatter.rb