Sha256: 997e26bfdfaa8f12361162bd0732a3d0d644cfcbb096fc05ca886ca6ec60876d

Contents?: true

Size: 1.88 KB

Versions: 4

Compression:

Stored size: 1.88 KB

Contents

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

4 entries across 4 versions & 1 rubygems

Version Path
markdown_exec-1.6 lib/method_sorter.rb
markdown_exec-1.5 lib/method_sorter.rb
markdown_exec-1.4.1 lib/method_sorter.rb
markdown_exec-1.4 lib/method_sorter.rb