Search code examples
ruby-on-railsgenerator

How to control text indentation when writing to file from custom generator


Writing my first generator. Struggling to figure out how to control the indentation.

I found a few methods here and here but it wasn't really clear to me how or if I can apply these.

The generator itself works as expected, it is just annoying that the indentation is wonky and I have to either ignore it or go into the file and fix it (which defeats the purpose of automating the generation of the file content).

Not really sure what relevant code would help, this is how I generate the additional code (one basic example).

  def add_site_wide
    inject_into_file './app/controllers/application_controller.rb',
    after: "class ApplicationController < ActionController::Base\n" do <<-'RUBY'
      default_form_builder MdbFormBuilder
    RUBY
    end
  end

Probably pretty easy to see what is going on, the only issue is the line being written default_form_builder MdbFormBuilder indented quite a bit, I can move it around and it does get placed correctly, but then the file generating it looks wonky and becomes hard to read with more content.

Is there a way to apply a method to this, or something else, that would allow me to also pass how many spaces to indent the text?

It really seems like something that should be doable, but I cannot find anything on how to achieve this.


Solution

  • Using the <<- will preserve whitespace on the string. You could use << but it would required you to put the end of string mark without any indentation aswell.

    To keep things pretty, the String class has a method for what you need and it is String#strip_heredoc. This will the indentation on every line.

    <<-EOS
    i
     have
      indentation
    EOS
    

    will result into

    "
    i
     have
      indentation
    "
    

    using

    <<-EOS.strip_heredoc
    i
     have
      no
       indentation
    EOS
    

    will result into

    "
    i
    have
    no
    indentation
    "
    

    You could use @engineersmnky sugestion with it to add indentation as needed

    <<-EOS.strip_heredoc.indent(2)
    i
     have
      two
       indentations
    EOS
    

    will result into

    "
      i
      have
      two
      indentations
    "