Feature #18450
openForce break in prettyprint
Description
Abstract¶
Support force-breaking a group in the std's 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.
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 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.
Updated by mame (Yusuke Endoh) almost 3 years ago
- Status changed from Open to Assigned
- Assignee set to akr (Akira Tanaka)
Could you explain a use case?
Updated by firasalkhalil (Firas al-Khalil) almost 3 years ago
mame (Yusuke Endoh) wrote in #note-1:
Could you explain a use case?
I am writing a code generator where in some cases I need to force-break the output code because it makes more sense for a human reader/reviewer:
Here's an example taken directly from my production code:
out.nest {
out.break if code.has_special_condition?
visitor.process(code[:body])
# =snip=
}
Updated by mame (Yusuke Endoh) over 2 years ago
- Related to Feature #18654: Enhancements to prettyprint added