Skip to content

Instantly share code, notes, and snippets.

@tsundokul
Last active November 19, 2018 09:40
Show Gist options
  • Save tsundokul/8851c658eef0f13e96e01bc2843fe336 to your computer and use it in GitHub Desktop.
Save tsundokul/8851c658eef0f13e96e01bc2843fe336 to your computer and use it in GitHub Desktop.
If you need to split a string to multiple lines within a Ruby script, this method will wrap it to a maximum line length (typically 80 characters)
#!/usr/bin/env ruby
# initial_indent: the offset after the equals sign for the first line of string
# add_indent: the offset used for the rest of the lines (say you have the string within an indented method)
def code_split(orig_s, initial_indent=0, add_indent=0, max_len=80)
# Simple chech before getting the work done
if (add_indent + 5) > max_len
raise "Not enough space left for lines."
end
s = orig_s.clone
sep = "-" * max_len
out = "" << sep + "\n"
s = s.gsub("\n", '\n').gsub("\r", '\r')
res_space = max_len - 4
bs = "\\"
unless initial_indent.zero? || res_space - initial_indent < 0
out << "\"#{s[0...(res_space - initial_indent)]}\" \\\n"
s = s[(res_space - initial_indent)..-1]
end
until s.empty?
line = " " * add_indent + '"'
line << s[0...(res_space - add_indent)]
nline = 0
while line[-1] == bs
nline += 1
line = line[0..-2]
end
out << line << "\" \\\n"
s = s[(res_space - add_indent - nline)..-1] || ""
end
out = out[0..-3] << "\n" + sep
puts out
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment