Search code examples
ruby-on-railsrubyruby-on-rails-4ruby-style-guide

What is the best way to refactor a long string line in ruby?


I have a line of code like this

"#{envelope_quantity} - envelope #{Budget::util_name(envelope_size)} #{Budget::util_name(envelope_paper)} #{Budget::util_name(envelope_color)} #{Budget::util_name(envelope_grammage)} #{Budget::util_name(envelope_model)} #{Budget::util_name(envelope_print)}"

too long, it's bad to read, and that's why RuboCop is warning me with it's Metrics::LineLength.

I would like to refactor it to not be a long line.

I know a lot of ways to do that, but I wonder which one would be the expected for the ruby style experts.

that static method util_name is needed to prevent nil when I need an empty string if it's nil.

def self.util_name(value)
  return '' if value.nil?
  value.name
end

Solution

  • You can try this

    str = "#{envelope_quantity} - envelope #{Budget::util_name(envelope_size)} "\
          "#{Budget::util_name(envelope_paper)} #{Budget::util_name(envelope_color)} "\
          "#{Budget::util_name(envelope_grammage)} #{Budget::util_name(envelope_model)} "\
          "#{Budget::util_name(envelope_print)}"
    

    this way you will be able to confine the string within max line length and also its slightly more readable than using join