Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How 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
like image 547
Ramon Marques Avatar asked Jun 10 '17 02:06

Ramon Marques


1 Answers

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

like image 109
Sujan Adiga Avatar answered Sep 16 '22 12:09

Sujan Adiga