From: "firasalkhalil (Firas al-Khalil)" Date: 2021-12-29T13:16:58+00:00 Subject: [ruby-core:106900] [Ruby master Feature#18450] Force break in prettyprint Issue #18450 has been reported by firasalkhalil (Firas al-Khalil). ---------------------------------------- Feature #18450: Force break in prettyprint https://bugs.ruby-lang.org/issues/18450 * Author: firasalkhalil (Firas al-Khalil) * Status: Open * Priority: Normal ---------------------------------------- # Abstract Support force-breaking a group in the std's [prettyprint](https://github.com/ruby/prettyprint) # Background There is a need to forcibly break a group and transform breakables into newlines. The library doesn't provide this possibility, directly, through its public API. # Proposal Add a single convenience function to the library's public class `PrettyPrint` # Implementation An implementation was submitted to the project's github repository as a [pull request](https://github.com/ruby/prettyprint/pull/2). Here's the patch: ``` diff --git a/lib/prettyprint.rb b/lib/prettyprint.rb index 188c2e6..1d675a7 100644 --- a/lib/prettyprint.rb +++ b/lib/prettyprint.rb @@ -236,6 +236,14 @@ class PrettyPrint end end + # This says "force a line break here". + # + # It will force the current group's "breakables" to break. + def break + breakable + current_group.break + end + # Groups line break hints added in the block. The line break hints are all # to be used or not. # diff --git a/test/test_prettyprint.rb b/test/test_prettyprint.rb index 27e7198..cf889d1 100644 --- a/test/test_prettyprint.rb +++ b/test/test_prettyprint.rb @@ -518,4 +518,31 @@ End end + +class Break < Test::Unit::TestCase # :nodoc: + def format() + PrettyPrint.format(''.dup) {|q| + q.group { + q.text 'abc' + q.breakable + q.text 'def' + q.group { + q.break + q.text 'ghi' + } + q.breakable + q.text 'jkl' + } + } + end + + def test_00_04 + expected = <<'End'.chomp +abc def +ghi jkl +End + assert_equal(expected, format()) + end +end + ``` # Evaluation It's a simple implementation with no caveats. # Discussion Even though it's a simple functionality, and the implementation is straightforward, getting to this point is not that obvious. This is why it might be helpful for other users who face such a need. Indeed, an issue was [opened](https://github.com/ruby/prettyprint/issues/1) not so long ago, and the proposed solution worked but not quite as expected. The provided implementation works as expected without tampering with the API's internals, and it's proven in production environment. # Summary This is a feature request for the `prettyprint` library: adding support for _force breaking_ a group. An implementation is provided as both a patch and a PR on github. -- https://bugs.ruby-lang.org/ Unsubscribe: