ruby - Indent multiline string in ERB -


i have string external library looks this:

s = "  things.each |thing|\n    thing += 5\n    thing.save\n  end\n\n" 

this input string isn't going change. need insert file using erb. e.g.:

erb = erb.new("<%= s %>") file.write("test.txt", erb.result(instance_eval('binding')) 

my problem indentation. without making changes string, file written this:

  things.each |thing|     thing += 5     thing.run   end 

note indentation. want do, however, insert text uniformly indented 2 spaces in, so:

    things.each |thing|       thing += 5       thing.run     end 

if this:

erb = erb.new("  <%= s %>") 

then first line indented.

    things.each |thing|     thing += 5     thing.run   end 

i can achieve modifying initial string..

erb = erb.new("<%= s.gsub(/  (\w)/, "    \\1") %>") 

.. feels bit messy. don't want in view. there way indent entire string in erb, or out of luck? think might be.

i don't think there builtin solution problem. not mean shouldn't build own :)

something should work:

class codeindenter < struct.new(:code, :indentation)   def self.indent(*args)     self.new(*args).indent   end    def separator     "\n"   end    def indent     code.split(separator).map |line|       indentation + line     end.join(separator)   end end  s = "  things.each |thing|\n    thing += 5\n    thing.save\n  end\n\n" puts codeindenter.indent(s, "  ") 

Comments

Popular posts from this blog

Ansible - ERROR! the field 'hosts' is required but was not set -

customize file_field button ruby on rails -

SoapUI on windows 10 - high DPI/4K scaling issue -