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-15.5.0 lib/gemsmith/gem/module_formatter.rb
gemsmith-15.4.0 lib/gemsmith/gem/module_formatter.rb
gemsmith-15.3.0 lib/gemsmith/gem/module_formatter.rb
gemsmith-15.2.0 lib/gemsmith/gem/module_formatter.rb
gemsmith-15.1.1 lib/gemsmith/gem/module_formatter.rb
gemsmith-15.1.0 lib/gemsmith/gem/module_formatter.rb
gemsmith-15.0.0 lib/gemsmith/gem/module_formatter.rb
gemsmith-14.11.0 lib/gemsmith/gem/module_formatter.rb
gemsmith-14.10.1 lib/gemsmith/gem/module_formatter.rb
gemsmith-14.10.0 lib/gemsmith/gem/module_formatter.rb
gemsmith-14.9.0 lib/gemsmith/gem/module_formatter.rb
gemsmith-14.8.0 lib/gemsmith/gem/module_formatter.rb
gemsmith-14.7.0 lib/gemsmith/gem/module_formatter.rb
gemsmith-14.6.0 lib/gemsmith/gem/module_formatter.rb
gemsmith-14.5.0 lib/gemsmith/gem/module_formatter.rb
gemsmith-14.4.0 lib/gemsmith/gem/module_formatter.rb
gemsmith-14.3.0 lib/gemsmith/gem/module_formatter.rb
gemsmith-14.2.0 lib/gemsmith/gem/module_formatter.rb
gemsmith-14.1.3 lib/gemsmith/gem/module_formatter.rb
gemsmith-14.1.2 lib/gemsmith/gem/module_formatter.rb