Sha256: d82b13c746538d3dc4fb42892690dddb32ca9430e832fa5681d1125d52297800

Contents?: true

Size: 1.88 KB

Versions: 8

Compression:

Stored size: 1.88 KB

Contents

# frozen_string_literal: true

require 'ripper'
require 'parser/current'

class MethodSorter
  def initialize(file_path)
    @file_path = file_path
  end

  def sort
    file_contents = File.read(@file_path)

    ast = Parser::CurrentRuby.parse(file_contents)

    # Find the class node
    class_node = ast.children.find { |node| node.type == :class }

    method_nodes = []

    # Look for method def nodes within each child node
    class_node.children.compact.each do |child|
      if child.type == :begin
        method_nodes += child.children.select { |n| n.type == :def }
      end
    end

    # Sort and process method nodes
    # class_node = ast.children.find { |node| node.type == :class }
    # unless class_node
    #   puts "No class node found in #{@file_path}"
    #   return
    # end

    # method_nodes = class_node.children.compact.select { |node|
    #   node.type == :def
    # }

    sorted_methods = method_nodes.sort_by { |n| n.children[0].to_s }
    ripper = Ripper.sexp(file_contents)
    lines = ripper.each_with_index.map { |sexp, index| [sexp, index] }

    method_ranges = get_method_ranges(lines, method_nodes)

    result = replace_method_ranges(lines, method_ranges, sorted_methods)

    puts result.compact.select { |v| v.is_a? String }.join("\n")
    # File.write(@file_path, result.join)
  end

  private

  def get_method_ranges(lines, method_nodes)
    method_nodes.map do |method_node|
      start_line = method_node.loc.line - 1
      end_line = start_line

      while end_line < lines.size && lines[end_line][0] !~ /^end/
        end_line += 1
      end

      (start_line..end_line)
    end
  end

  def replace_method_ranges(lines, ranges, sorted_methods)
    result = lines.dup

    ranges.each_with_index do |range, index|
      result[range] = sorted_methods[index].loc.expression.source.split("\n")
    end

    result
  end
end

sorter = MethodSorter.new(ARGV[0])
sorter.sort

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
markdown_exec-1.8.7 lib/method_sorter.rb
markdown_exec-1.8.6 lib/method_sorter.rb
markdown_exec-1.8.5 lib/method_sorter.rb
markdown_exec-1.8.4 lib/method_sorter.rb
markdown_exec-1.8.2 lib/method_sorter.rb
markdown_exec-1.8.1 lib/method_sorter.rb
markdown_exec-1.8 lib/method_sorter.rb
markdown_exec-1.7 lib/method_sorter.rb