Skip to content

Commit

Permalink
Fix comment reproduction when ranges are not present
Browse files Browse the repository at this point in the history
* Closes #20
  • Loading branch information
mbj committed Dec 29, 2013
1 parent e8021ac commit 0274424
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 7 deletions.
2 changes: 1 addition & 1 deletion config/flay.yml
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
---
threshold: 13
total_score: 463
total_score: 465
48 changes: 42 additions & 6 deletions lib/unparser/comments.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,20 @@ module Unparser
# Holds the comments that remain to be emitted
class Comments

# Proxy to singleton
#
# NOTICE:
# Delegating to stateless helpers is a pattern I saw many times in our code.
# Maybe we should make another helper module? include SingletonDelegator.new(:source_range) ?
#
# @return [undefined]
#
# @api private
#
def source_range(*arguments)
self.class.source_range(*arguments)
end

# Initialize object
#
# @param [Array] comments
Expand All @@ -26,9 +40,10 @@ def initialize(comments)
# @api private
#
def consume(node, source_part = :expression)
location = node.location
return unless location
@last_range_consumed = location.public_send(source_part)
range = source_range(node, source_part)
if range
@last_range_consumed = range
end
end

# Take end-of-line comments
Expand Down Expand Up @@ -63,15 +78,36 @@ def take_all
# @api private
#
def take_before(node, source_part)
location = node.location
if location.respond_to?(source_part)
range = location.public_send(source_part)
range = source_range(node, source_part)
if range
take_while { |comment| comment.location.expression.end_pos <= range.begin_pos }
else
EMPTY_ARRAY
end
end

# Return source location part
#
# FIXME: This method should not be needed. It does to much inline signalling.
#
# @param [Parser::AST::Node] node
# @param [Symbol] part
#
# @return [Parser::Source::Range]
# if present
#
# @return [nil]
# otherwise
#
# @api private
#
def self.source_range(node, part)
location = node.location
if location && location.respond_to?(part)
location.public_send(part)
end
end

private

# Take comments while the provided block returns true
Expand Down
10 changes: 10 additions & 0 deletions spec/unit/unparser_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -1212,6 +1212,16 @@ def foo
# last
RUBY

assert_generates <<-'RUBY', <<-'RUBY'
foo if bar
# comment
RUBY
if bar
foo
end
# comment
RUBY

assert_source <<-'RUBY'
def noop
# do nothing
Expand Down

0 comments on commit 0274424

Please sign in to comment.