Class: Unparser::Comments

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

Overview

Holds the comments that remain to be emitted

Instance Method Summary collapse

Constructor Details

#initialize(comments) ⇒ undefined

Initialize object

Parameters:

  • comments (Array)


12
13
14
15
# File 'lib/unparser/comments.rb', line 12

def initialize(comments)
  @comments = comments.dup
  @last_range_consumed = @eol_text_to_skip = nil
end

Instance Method Details

#consume(node, source_part = :expression) ⇒ undefined

Consume part or all of the node

Parameters:

  • node (Parser::AST::Node)
  • source_part (Symbol) (defaults to: :expression)

Returns:

  • (undefined)


24
25
26
27
28
# File 'lib/unparser/comments.rb', line 24

def consume(node, source_part = :expression)
  location = node.location
  return unless location
  @last_range_consumed = location.public_send(source_part)
end

#skip_eol_comment(comment_text) ⇒ undefined

Skip any EOL comment with the specified text next time they’re taken

Parameters:

  • comment_text (String)

Returns:

  • (undefined)


36
37
38
# File 'lib/unparser/comments.rb', line 36

def skip_eol_comment(comment_text)
  @eol_text_to_skip = comment_text
end

#take_allArray

Take all remaining comments

Returns:

  • (Array)


57
58
59
# File 'lib/unparser/comments.rb', line 57

def take_all
  take_while { true }
end

#take_before(node, source_part) ⇒ Array

Take comments appear in the source before the specified part of the node

Parameters:

  • node (Parser::AST::Node)
  • source_part (Symbol)

Returns:

  • (Array)


68
69
70
71
72
73
74
75
76
# File 'lib/unparser/comments.rb', line 68

def take_before(node, source_part)
  location = node.location
  if location.respond_to?(source_part)
    range = location.public_send(source_part)
    take_while { |comment| comment.location.expression.end_pos <= range.begin_pos }
  else
    EMPTY_ARRAY
  end
end

#take_eol_commentsArray

Take end-of-line comments

Returns:

  • (Array)


44
45
46
47
48
49
50
51
# File 'lib/unparser/comments.rb', line 44

def take_eol_comments
  text_to_skip = @eol_text_to_skip
  @eol_text_to_skip = nil
  return [] unless @last_range_consumed
  comments = take_up_to_line(@last_range_consumed.end.line)
  eol_comments = unshift_documents(comments)
  eol_comments.reject { |comment| comment.text == text_to_skip }
end