Search code examples
rubyoptparse

How to best wrap Ruby optparse code and output?


For the following code, which according to the style guide should be wrapped at 80 chars:

opts.on('--scores_min <uint>', Integer, 'Drop reads if a single position in ',
                                        'the index have a quality score ',
                                        'below scores_main (default= ',
                                        "#{DEFAULT_SCORE_MIN})") do |o|
  options[:scores_min] = o
end

The resulting output is:

    --scores_min <uint>          Drop reads if a single position in
                                 the index have a quality score
                                 below scores_main (default=
                                 16)

Which wraps at 72 chars and looks wrong :o(

I really want it wrapped at 80 chars and aligned like this:

    --scores_min <uint>          Drop reads if a single position in the
                                 index have a quality score below
                                 scores_min (default=16)

How can this be achieved in a clever way?


Solution

  • So I think the solution is to follow the Ruby Style Guide:

    When using heredocs for multi-line strings keep in mind the fact that they preserve leading whitespace. It's a good practice to employ some margin based on which to trim the excessive whitespace.

    code = <<-END.gsub(/^\s+\|/, '')
      |def test
      |  some_method
      |  other_method
      |end
    END
    # => "def test\n  some_method\n  other_method\nend\n"
    

    [EDIT] In Ruby 2.3 you can do (same ref):

    code = <<~END
      def test
        some_method
        other_method
      end
    END