Pastel Ruby Library

repository·master·Indexed 20 days ago

https://github.com/piotrmurach/pastel

A minimal Ruby library for terminal output styling that provides an intuitive API for applying colors and styles to strings without monkey-patching the String class. It supports foreground and background colors, generic styles like bold and italic, and features for creating reusable styles via detach, dynamic styling with decorate, and custom color aliases.

Tokens
2.5K
Snippets
17
Records
20
Agent score
68%

What's inside Pastel

  1. Basic Usage of Pastel

    master

    Pastel provides an intuitive API for styling strings without monkey-patching the String class. It returns a colored string rather than printing it, so you must call puts or another output method yourself.

    Basic coloring:

    pastel = Pastel.new
    puts pastel.red("Unicorns!")

    Chainable styles:

    pastel.red.on_green.bold("Unicorns!")

    Combining styled and unstyled strings:

    pastel.red("Unicorns") + " will rule " + pastel.green("the World!")

    Passing multiple arguments:

    pastel.red("Unicorns", "are", "running", "everywhere!")

    Nesting styles:

    pastel.red("Unicorns ", pastel.on_green("everywhere!"))

    Nesting using blocks:

    pastel.red.on_green("Unicorns") {
      green.on_red("will ", "dominate") {
        yellow("the world!")
      }
    }
    pastel = Pastel.new
    puts pastel.red("Unicorns!")
  2. Initialize a Pastel::Color instance

    master

    To use Pastel for coloring strings, create an instance of Pastel::Color. You can control whether coloring is enabled and whether styles should be applied to every line in a multi-line string.

    • enabled: (Optional) Set to false to disable all coloring for this instance. Defaults to nil (which typically follows system defaults).
    • eachline: (Optional) If set to true, the color codes will be applied to every line in a multi-line string, ensuring each line is wrapped with the appropriate reset codes.
    color = Pastel::Color.new(enabled: true, eachline: true)
  3. Use `detach` to create reusable styles

    master

    The detach method allows you to create a reusable style object. This is useful for frequently used color combinations. A detached object can be invoked using .call, the shorthand .(), or array-like access [].

    notice = pastel.blue.bold.detach
    
    notice.call("Unicorns running")
    notice.("Unicorns running")
    notice["Unicorns running"]
    notice = pastel.blue.bold.detach
    notice.("Unicorns running")
  4. Use `decorate` for dynamic styling

    master

    The decorate method is a lower-level call used when color attributes are provided as a list of parameters (e.g., generated dynamically). It takes the string to style as the first argument, followed by any number of color attributes.

    pastel.decorate("Unicorn", :green, :on_blue, :bold)
    pastel.decorate("Unicorn", :green, :on_blue, :bold)
  5. Create color aliases

    master

    You can create custom names for existing color combinations using alias_color. Aliases are global and affect all callers in the same process.

    pastel.alias_color(:funky, :red, :bold)
    
    # Now you can use :funky
    pastel.funky.on_green("unicorn") # uses :red and :bold

    You can also define aliases via the PASTEL_COLORS_ALIASES environment variable.

    Environment Variable Format: PASTEL_COLORS_ALIASES="newcolor_1=red,newcolor_2=on_green,funky=red.bold"

    pastel.alias_color(:funky, :red, :bold)
  6. Use `undecorate` to parse color sequences

    master

    The undecorate method converts color escape sequences in a string into a list of hash objects. Each hash contains keys like :foreground, :background, :text, and/or :style.

    pastel.undecorate("\e[32mfoo\e[0m \e[31mbar\e[0m")
    # => [{foreground: :green, text: "foo"}, {text: " "}, {foreground: :red, text: "bar"}]
    pastel.undecorate("\e[32mfoo\e[0m \e[31mbar\e[0m")
  7. Handle multiline strings with `eachline`

    master

    By default, Pastel puts color codes at the beginning and end of the entire string. For multiline strings, this can cause background colors to spill into subsequent lines in some terminals/pagers.

    To prevent this, use the eachline option to specify a delimiter (usually \n). This ensures each line is separately colored and reset.

    pastel = Pastel.new(eachline: "\n")
    pastel.red("foo\nbar")  # => "\e[31mfoo\e[0m\n\e[31mbar\e[0m"
    pastel = Pastel.new(eachline: "\n")
  8. Use `strip` to remove color sequences

    master

    The strip method removes color escape sequences from strings while preserving movement codes or other escape sequences. It returns either a single string or an array of modified strings depending on the input. The original arguments are not modified.

    pastel.strip("\e[1A\e[1m\e[34mbold blue text\e[0m")  # => "\e[1Abold blue text"
    pastel.strip("\e[1A\e[1m\e[34mbold blue text\e[0m")
  9. Check color support and enable/disable coloring

    master

    Use enabled? to detect if the terminal supports coloring. If support is not detected, no styling will be applied.

    To force coloring on:

    pastel = Pastel.new(enabled: true)

    To suppress color when output is redirected to a file (e.g., when using stdout or stderr), you can initialize Pastel based on whether the stream is a TTY:

    stdout_pastel = Pastel.new(enabled: $stdout.tty?)
    stderr_pastel = Pastel.new(enabled: $stderr.tty?)
    stdout_pastel = Pastel.new(enabled: $stdout.tty?)
  10. Reference: Supported Colors and Styles

    master

    Pastel supports 16 basic colors, 8 styles, and 16 bright color pairs.

    Foreground Colors: black, red, green, yellow, blue, magenta, cyan, white, bright_black, bright_red, bright_green, bright_yellow, bright_blue, bright_magenta, bright_cyan, bright_white

    Background Colors (use on_ prefix): on_black, on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan, on_white, on_bright_black, on_bright_red, on_bright_green, on_bright_yellow, on_bright_blue, on_bright_magenta, on_bright_cyan, on_bright_white

    Generic Styles: clear, bold, dim, italic, underline, inverse, hidden, strikethrough

  11. Reference: Pastel API Methods

    master

    The following methods are available on a Pastel instance:

    • styles: Returns a full list of supported styles with corresponding color codes.
    • lookup(color_or_symbol): Translates a color name into its ANSI escape code (e.g., pastel.lookup(:red)).
    • valid?(*attributes): Returns true if all provided attribute strings or symbols are known, false otherwise.
    • colored?(string): Returns true if the string contains color escape codes.
    • eachline(delimiter): (Option during initialization) Sets the line delimiter for multiline coloring.