Sha256: 159d3771b902f1d8f3cd19c8721c72638295f2968c765b33c8990935be596455

Contents?: true

Size: 1.19 KB

Versions: 37

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.lstrip.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

37 entries across 37 versions & 1 rubygems

Version Path
gemsmith-14.1.1 lib/gemsmith/gem/module_formatter.rb
gemsmith-14.1.0 lib/gemsmith/gem/module_formatter.rb
gemsmith-14.0.2 lib/gemsmith/gem/module_formatter.rb
gemsmith-14.0.1 lib/gemsmith/gem/module_formatter.rb
gemsmith-14.0.0 lib/gemsmith/gem/module_formatter.rb
gemsmith-13.8.0 lib/gemsmith/gem/module_formatter.rb
gemsmith-13.7.2 lib/gemsmith/gem/module_formatter.rb
gemsmith-13.7.1 lib/gemsmith/gem/module_formatter.rb
gemsmith-13.7.0 lib/gemsmith/gem/module_formatter.rb
gemsmith-13.6.0 lib/gemsmith/gem/module_formatter.rb
gemsmith-13.5.0 lib/gemsmith/gem/module_formatter.rb
gemsmith-13.4.0 lib/gemsmith/gem/module_formatter.rb
gemsmith-13.3.0 lib/gemsmith/gem/module_formatter.rb
gemsmith-13.2.0 lib/gemsmith/gem/module_formatter.rb
gemsmith-13.1.0 lib/gemsmith/gem/module_formatter.rb
gemsmith-13.0.0 lib/gemsmith/gem/module_formatter.rb
gemsmith-12.4.0 lib/gemsmith/gem/module_formatter.rb