Sha256: 5f1772df3c81fc729fbdae0d1f926b7318962a72886e1f3f708296f29ddc0429

Contents?: true

Size: 1.19 KB

Versions: 7

Compression:

Stored size: 1.19 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 self.indent length = 0
        "  " * length
      end

      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 + "#{self.class.indent index}module #{module_name}\n"
        end
      end

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

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

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
gemsmith-10.4.2 lib/gemsmith/gem/module_formatter.rb
gemsmith-10.4.1 lib/gemsmith/gem/module_formatter.rb
gemsmith-10.4.0 lib/gemsmith/gem/module_formatter.rb
gemsmith-10.3.0 lib/gemsmith/gem/module_formatter.rb
gemsmith-10.2.0 lib/gemsmith/gem/module_formatter.rb
gemsmith-10.1.0 lib/gemsmith/gem/module_formatter.rb
gemsmith-10.0.0 lib/gemsmith/gem/module_formatter.rb