ERB::Formatter

repository·main·Indexed 42 days ago

https://github.com/nebulab/erb-formatter

A high-speed formatter for ERB (Embedded Ruby) files that provides HTML-like formatting and handles Ruby block indentation. It includes a Ruby API via ERB::Formatter.format, a command-line tool (erb-format), and supports Tailwind CSS class sorting and CI/CD integration with a --fail-level check flag.

Tokens
2.3K
Snippets
12
Records
14
Agent score
52%

What's inside ERB::Formatter

  1. Configure ERB::Formatter in various editors

    main

    Visual Studio Code

    Install the Ruby ERB::Formatter 🪜 extension.

    (Neo)VIM ALE

    Enable it as a fixer in your ALE configuration:

    let g:ale_fixers = {
    \   'eruby': ['erb-formatter'],
    \}

    Neovim conform.nvim

    Specify erb_format for the eruby filetype in your conform setup:

    formatters_by_ft = {
      eruby = { "erb_format" },
    },

    Zed

    Configure settings.json to use erb-format as an external command:

    "languages": {
      "ERB": {
        "formatter": {
          "external": {
            "command": "erb-format",
            "arguments": ["--stdin", "--print-width", "80"]
          }
        }
      }
    }

    TextMate

    Create a command with these settings:

    • Scope selector: text.html.erb
    • Semantic class: callback.document.will-save
    • Input: document → text
    • Output: replace document → text
    • Caret placement: line-interpolation

    Use this script for the command:

    #!/usr/bin/env bash
    
    cd "$TM_PROJECT_DIRECTORY"
    bundle exec erb-format --stdin-filename "$TM_FILEPATH" < /dev/stdin 2> /dev/stdout
  2. Use the ERB::Formatter Ruby API

    main

    You can use the ERB::Formatter.format method to format ERB strings programmatically within your Ruby applications.

    require 'erb/formatter'
    
    formatted = ERB::Formatter.format <<-ERB
    <div        >
                asdf
                      <% if 123%>
                          <%='foobar'%> <%end-%>
               </div>
    ERB
    
    # => "<div>\n  asdf\n  <% if 123 %>\n    <%= 'foobar' %>\n  <% end -%>
    </div>\n"
  3. Handle ERB formatting errors

    main

    If the ERB or HTML structure is invalid (e.g., unmatched tags or bad attribute syntax), ERB::Formatter raises an ERB::Formatter::Error.

    Error messages include:

    • The filename and line number.
    • The specific error message (e.g., Unmatched close tag, Bad attribute, or Unknown tag).
    • A visual representation of the formatted output up to the error point.
    • A stack trace showing the tag stack at the time of the error.
  4. Use ERB::Formatter from the command line

    main

    The erb-format CLI tool allows you to format files in-place or via stdin/stdout.

    Update files in-place: Use the --write flag to modify files directly.

    Use stdin/stdout: Useful for editor integrations. Pipe content into the command using --stdin.

    Run erb-format --help to see all available options.

    # Update files in-place
    $ erb-format app/views/**/*.html.erb --write
    
    # Use stdin/stdout
    $ echo "<div       > asdf  <% if 123%> <%='foobar'%> <%end-%>  </div>" | erb-format --stdin
  5. Configure ERB::Formatter options

    main

    To use advanced configuration, instantiate ERB::Formatter.new with the following options:

    • source (String): The ERB content to format.
    • line_width (Integer): The maximum line length (default: 80).
    • single_class_per_line (Boolean): If true, each CSS class in a class attribute will be placed on its own line. (default: false).
    • filename (String): The name of the file being formatted, used in error messages (default: '(erb)').
    • css_class_sorter (Proc): A proc used to sort CSS classes within the class attribute.
    • debug (Boolean): Enables debug output (uses $DEBUG).
    formatter = ERB::Formatter.new(
      source,
      line_width: 100,
      single_class_per_line: true,
      filename: 'views/index.html.erb',
      css_class_sorter: ->(classes) { classes.sort }
    )
    
    puts formatter.html
  6. Format ERB content with ERB::Formatter.format

    main

    The primary way to use this library is via the ERB::Formatter.format class method. It takes a source string and returns a formatted version of the ERB content. You can optionally provide a filename for better error reporting.

    By default, it uses a line width of 80 characters. You can customize the formatting behavior by instantiating ERB::Formatter.new directly if you need more granular control over options like line_width, single_class_per_line, or css_class_sorter.

    require 'erb/formatter'
    
    source = "<div>\n  <% if true %>\n    <%= 'hello' %>\n  <% end %>\n</div>"
    formatted = ERB::Formatter.format(source)
    puts formatted
  7. Reference: ERB::Formatter CLI options

    main

    The following flags are available for the erb-formatter command-line tool:

    FILENAME...           The files to be formatted
    
    -w, --[no-]write      Write file
    --stdin-filename FILEPATH  Set the stdin filename (implies --stdin)
    --[no-]stdin           Read the file from stdin
    --print-width WIDTH   Set the formatted output width
    --single-class-per-line  Print each class on a separate line
    --tailwind-output-path PATH  Set the path to the tailwind output file
    --[no-]debug           Enable debug mode
    --fail-level LEVEL     'check' exits(1) on any formatting changes
    -h, --help             Prints this help
    -v, --version          Show ERB::Formatter version number and quit
  8. Use the erb-format CLI to format files

    main

    The erb-format executable is a command-line interface for formatting ERB files. It is invoked via the terminal and processes arguments passed through ARGV. To use it, ensure the erb-formatter gem is installed and the executable is in your PATH.

    # Example usage (exact flags depend on the underlying CommandLine implementation)
    ```bash
    erb-format path/to/file.erb
  9. Configure Tailwind CSS class sorting

    main

    You can integrate Tailwind CSS class sorting by providing the path to your generated Tailwind CSS output file using the --tailwind-output-path flag. This allows the formatter to use the actual CSS selectors from your project to sort classes within your ERB templates.

    erb-formatter my_template.erb --tailwind-output-path ./dist/output.css
  10. Read ERB content from stdin

    main

    You can pipe ERB content into the formatter using the --stdin flag. If you provide a filename via --stdin-filename, it will be used as the filename for the formatting process.

    # Basic stdin usage
    cat template.erb | erb-formatter --stdin
    
    # Stdin with a specific filename
    echo "<% if true %>hello<% end %>" | erb-formatter --stdin --stdin-filename test.erb