Sha256: c59c3c16e873611fe8e72f75c4a34d8384642a35249e8811666c9697ec837f6d

Contents?: true

Size: 1.33 KB

Versions: 1

Compression:

Stored size: 1.33 KB

Contents

# frozen_string_literal: true

module Pragmater
  # Formats pragma comments in a consistent manner.
  class Formatter
    def self.shebang_format
      /
        \A       # Start of line.
        \#       # Start of comment.
        \!       # Bang.
        \s?      # Space - optional.
        \/.*ruby # Absolute path to Ruby program.
        \Z       # End of line.
      /x
    end

    def self.pragma_format
      /
        \A  # Start of line.
        \#  # Start of comment.
        \s? # Space - optional.
        \w+ # Key - 1 or more word characters only.
        \:  # Key and value delimiter.
        \s? # Space - optional.
        .+  # Value - 1 or more characters.
        \Z  # End of line.
      /x
    end

    def initialize comment
      @comment = comment
    end

    def format_shebang
      return comment unless comment =~ self.class.shebang_format

      _, path = comment.split "!"
      "#! #{path.strip}"
    end

    def format_pragma
      return comment unless comment =~ self.class.pragma_format

      key, value = comment.split ":"
      "# #{key.gsub(/\#\s?/, "")}: #{value.strip}"
    end

    def format
      case comment
        when self.class.shebang_format then format_shebang
        when self.class.pragma_format then format_pragma
        else comment
      end
    end

    private

    attr_reader :comment
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
pragmater-0.1.0 lib/pragmater/formatter.rb