Sha256: 795b3e4547f8dc668d0882b723ad28064a87dd40cf5237b27f7979e38149af07

Contents?: true

Size: 1.13 KB

Versions: 10

Compression:

Stored size: 1.13 KB

Contents

# frozen_string_literal: true

require "refinements/strings"

module Rubysmith
  module Renderers
    # Renders single or multiple modules with correct, two-space indentation for templates.
    class Namespace
      using Refinements::Strings

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

      def call(content = nil) = "#{prefix}#{body content}#{suffix}"

      private

      attr_reader :namespace, :modules, :depth

      def prefix
        modules.each.with_index.reduce "" do |snippet, (module_name, index)|
          %(#{snippet}#{"module".indent index} #{module_name}\n)
        end
      end

      # :reek:FeatureEnvy
      def body content
        String(content).lstrip.split("\n").reduce "" do |snippet, line|
          next "#{snippet}\n" if line.blank?

          "#{snippet}#{line.gsub(/^\s{2}/, "").indent depth + 1}\n"
        end
      end

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

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
rubysmith-1.2.0 lib/rubysmith/renderers/namespace.rb
rubysmith-1.1.1 lib/rubysmith/renderers/namespace.rb
rubysmith-1.1.0 lib/rubysmith/renderers/namespace.rb
rubysmith-1.0.0 lib/rubysmith/renderers/namespace.rb
rubysmith-0.16.1 lib/rubysmith/renderers/namespace.rb
rubysmith-0.16.0 lib/rubysmith/renderers/namespace.rb
rubysmith-0.15.0 lib/rubysmith/renderers/namespace.rb
rubysmith-0.14.0 lib/rubysmith/renderers/namespace.rb
rubysmith-0.13.0 lib/rubysmith/renderers/namespace.rb
rubysmith-0.12.0 lib/rubysmith/renderers/namespace.rb