Class: Proc

Inherits:
Object
  • Object
show all
Defined in:
lib/proc_to_ast.rb

Instance Method Summary collapse

Instance Method Details

#to_ast(retry_limit = 20) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/proc_to_ast.rb', line 45

def to_ast(retry_limit = 20)
  filename, linenum = source_location
  file = File.open(filename, "rb")

  (linenum - 1).times { file.gets }
  buf = []
  try_count = 0

  parser = Parser::CurrentRuby.default_parser
  parser.diagnostics.consumer = ->(diagnostic) {} # suppress error message
  begin
    parser.reset
    try_count += 1

    buf << file.gets
    source = buf.join.force_encoding(parser.default_encoding)

    source_buffer = Parser::Source::Buffer.new(filename, linenum)
    source_buffer.source = source
    node = parser.parse(source_buffer)
    block_nodes = ProcToAst::Traverser.new.traverse_node(node)
    if block_nodes.length == 1
      block_nodes.first
    else
      raise ProcToAst::MultiMatchError
    end
  rescue Parser::SyntaxError
    retry if try_count < retry_limit
  end
end

#to_source(highlight: false) ⇒ Object



76
77
78
79
80
81
82
83
# File 'lib/proc_to_ast.rb', line 76

def to_source(highlight: false)
  source = Unparser.unparse(to_ast)
  if highlight
    CodeRay.scan(source, :ruby).terminal
  else
    source
  end
end