Module: RuboCop::Cop::CheckSingleLineSuitability
Relationships & Source Files | |
Extension / Inclusion / Inheritance Descendants | |
Included In:
| |
Defined in: | lib/rubocop/cop/mixin/check_single_line_suitability.rb |
Overview
Checks for code on multiple lines that could be rewritten on a single line
without changing semantics or exceeding the Max
parameter of Layout/LineLength
.
Instance Method Summary
- #suitable_as_single_line?(node) ⇒ Boolean
- #comment_within?(node) ⇒ Boolean private
- #max_line_length private
- #safe_to_split?(node) ⇒ Boolean private
- #to_single_line(source) private
- #too_long?(node) ⇒ Boolean private
Instance Method Details
#comment_within?(node) ⇒ Boolean
(private)
# File 'lib/rubocop/cop/mixin/check_single_line_suitability.rb', line 34
def comment_within?(node) comment_line_numbers = processed_source.comments.map { |comment| comment.loc.line } comment_line_numbers.any? do |comment_line_number| comment_line_number >= node.first_line && comment_line_number <= node.last_line end end
#max_line_length (private)
[ GitHub ]# File 'lib/rubocop/cop/mixin/check_single_line_suitability.rb', line 30
def max_line_length config.for_cop('Layout/LineLength')['Max'] end
#safe_to_split?(node) ⇒ Boolean
(private)
# File 'lib/rubocop/cop/mixin/check_single_line_suitability.rb', line 42
def safe_to_split?(node) node.each_descendant(:if, :case, :kwbegin, :def, :defs).none? && node.each_descendant(:dstr, :str).none? { |n| n.heredoc? || n.value.include?("\n") } && node.each_descendant(:begin, :sym).none? { |b| !b.single_line? } end
#suitable_as_single_line?(node) ⇒ Boolean
# File 'lib/rubocop/cop/mixin/check_single_line_suitability.rb', line 8
def suitable_as_single_line?(node) !too_long?(node) && !comment_within?(node) && safe_to_split?(node) end
#to_single_line(source) (private)
[ GitHub ]# File 'lib/rubocop/cop/mixin/check_single_line_suitability.rb', line 21
def to_single_line(source) source .gsub(/" *\\\n\s*'/, %q(" + ')) # Double quote, backslash, and then single quote .gsub(/' *\\\n\s*"/, %q(' + ")) # Single quote, backslash, and then double quote .gsub(/(["']) *\\\n\s*\1/, '') # Double or single quote, backslash, then same quote .gsub(/\n\s*(?=(&)?\.\w)/, '') # Extra space within method chaining which includes `&.` .gsub(/\s*\\?\n\s*/, ' ') # Any other line break, with or without backslash end
#too_long?(node) ⇒ Boolean
(private)
# File 'lib/rubocop/cop/mixin/check_single_line_suitability.rb', line 16
def too_long?(node) lines = processed_source.lines[(node.first_line - 1)...node.last_line] to_single_line(lines.join("\n")).length > max_line_length end